[英]JavaScript 'function invoked' event listener
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
是否再次调用addAndRemove
。 如果要请求一个新的Ajax请求,我只想取消它。 我怎样才能做到这一点?
您需要使用闭包在函数中创建状态。
您可以通过这种方式重构您的功能。
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都将指向相同的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.