1

I have a question regarding ES6 modules and how to correctly call functions between them as a callback.

Take "page_API.js", Upon data being recieved the callback function is called

// Make a call to our server, Once we've recieved data we'll call our callback

import {requestExecuteAsync} from "../xml_functions";

export const getData = () => {
    requestExecuteAsync('api/getData', "dataRecieved");
};

 export const dataRecieved = () => {
     alert('Recieved Data');
 };

Now in my "xml_functions.js" where I handle this requestExecuteAsync and more, I would like to call the dataRecieved once the server has responded.

Previously the codebase I work with consisted of many JS files, with all functions living in the global namespace, so the function worked like this

// once data has been retrieved from server
if (callbackparamsArr.length) {
    window[callback](res, callbackparamsArr);
} else {
    window[callback](res);
}

However now the callback function is undefined in the window as it no longer has scope of dataRecieved.

I've tried including the dataRecieved function inside the xml_functions

import { dataRecieved } from "../MyPage/MyPage_API.js";

and then just call

[callback](res)

but due to the "dataRecieved" import getting given a different string as defined in requestExecuteAsync (E.G it will be called "_Data_Recieved_" instead of "dataRecieved" i'm not sure what to do.

Any help would be much appreciated!

Thanks

4

1 回答 1

3

You should not pass the name of the callback function you want to call. Just pass the function itself:

import {requestExecuteAsync} from "../xml_functions";

export function getData() {
    requestExecuteAsync('api/getData', dataReceived);
//                                     ^^^^^^^^^^^^
}
export function dataReceived() {
    alert('Recieved Data');
}

export function requestExecuteAsync(path, callback) {
    …
    if (typeof callback == "function") callback(res);
    …
}

But since you're using ES6, you might want to have a look at promises so that you don't need to pass callback functions around at all.

于 2016-10-25T12:09:27.920 回答