0

我有一些代碼,異步調用谷歌地圖:發現通過與谷歌地圖API的回調來傳遞信息的好方法

var directionsService = new google.maps.DirectionsService; 
directionsService.route(arg1, callback); 
directionsService.route(arg2, callback); 
directionsService.route(arg3, callback); 

function callback(response, status) { 
    // complex function here 
} 

眼下在單件的每個數據回調的結果存儲在一個全局變量。設計有所增加,現在我想在每個回調中包含一個參數。但我不能直接這樣做,因爲我不控制directionsService.route。這也讓我覺得這已經是解決問題的一種迂迴方式;我寧願將arg1, arg2, arg3及其參數傳遞給一個可以處理異步內容並在所有內容都返回時清理的函數。關於什麼是最好的方式去做這件事的任何建議?

我可以通過添加另一個全局並在調用之間更新它來深入挖掘我的洞。我可以爲directionsService.route編寫一個封裝器,將它封裝在另一個回調間接層中。我可以嘗試將回調格式強制轉換爲像async這樣的庫所需的匹配。我可以編寫幾個版本的回調函數,或者用函數發生器替換它。這些選項是否合理?有什麼更好的嗎?

老實說,這是一個小項目,我不需要一些可以很好地擴展的東西,但僅僅爲了我自己的安心,我想要一些不好的東西,有點幹。

回答

1

我寫了一個簡單的代碼巫婆調用一個事件與回調函數。當事件發送時,你只需要一個簡單的eventListener,以及你想要的任何參數,女巫稱你的大功能。

這是我的代碼:

var directionsService = new google.maps.DirectionsService; 

// Listen for the event. 
var aParameter = 35; 
window.addEventListener('build', function (e) { console.log("OK EVENT. With a prameter: " + aParameter); /* Now, call a function with parameters:*/ aFunction (aParameter); }, false); 

directionsService.route(arg1, callback); 

function callback() { 
    console.log("OK CALLBACK."); 
    var event = new Event('build'); 
    // Dispatch the event. 
    window.dispatchEvent(event); 
} 

function aFunction (parameter) { 
    console.log (parameter); 
} 

您也可以調度的事件與參數,如用狀況:

var event = new CustomEvent('build', { detail: elem.dataset.time }); 

function eventHandler(e) { 
    console.log('The time is: ' + e.detail); 
} 

諮詢MDN page有關事件。

告訴我,如果你有一些問題。