function addAndRemove() {
if (mapData.initialZoom && !cameraStatus.locked) {
cameraStatus.locked = true;
var ajaxRequest = null;
var abortMission = setTimeout(function () {
/* Here is where I need the event listener.
* If the function is called again then we need to
* cancel our existing ajax request */
if (ajaxRequest) {
ajaxRequest.abort();
updatePrompt({text: "Cancelled ajax"});
}
cameraStatus.locked = false;
}, 1000);
}
}
正如我在代码中的评论中所述,我需要能够在执行过程中听取是否再次调用addAndRemove
。我只想取消现有的Ajax请求,如果请求了新的Ajax请求。我怎么能这样做?
答案 0 :(得分:3)
您需要使用闭包在函数中创建状态。
你可以用这种方式重构你的功能。
var addAndRemove = (function(){
var ajaxRequest = null; // --> move ajaxRequest variable here
return function () {
if (mapData.initialZoom && !cameraStatus.locked) {
cameraStatus.locked = true;
var abortMission = setTimeout(function () {
/* Here is where I need the event listener.
* If the function is called again then we need to
* cancel our existing ajax request */
if (ajaxRequest) {
ajaxRequest.abort();
updatePrompt({text: "Cancelled ajax"});
}
cameraStatus.locked = false;
}, 1000);
}
}
}());
无论调用函数的时间长短,ajaxRequest都将指向相同的引用。