[英]Calling another module function as callback [ES6]
我有一個關於ES6模塊的問題以及如何正確調用它們之間的函數作為回調。
取“page_API.js”,收到數據后,調用回調函數
// 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');
};
現在在我處理此requestExecuteAsync等的“xml_functions.js”中,我想在服務器響應后調用dataRecieved。
以前我使用的代碼庫包含許多JS文件,所有函數都存在於全局命名空間中,所以函數就像這樣工作
// once data has been retrieved from server
if (callbackparamsArr.length) {
window[callback](res, callbackparamsArr);
} else {
window[callback](res);
}
但是現在回調函數在窗口中未定義,因為它不再具有dataRecieved范圍。
我已經嘗試在xml_functions中包含dataRecieved函數
import { dataRecieved } from "../MyPage/MyPage_API.js";
然后打電話
[callback](res)
但是由於“dataRecieved”導入獲得了requestExecuteAsync中定義的不同字符串(EG將被稱為“_Data_Recieved_”而不是“dataRecieved”,我不知道該怎么做。
任何幫助將非常感激!
謝謝
您不應傳遞要調用的回調函數的名稱。 只需傳遞函數本身:
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);
…
}
但是,由於您使用的是ES6,因此您可能需要查看promises,以便根本不需要傳遞回調函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.