简体   繁体   English

JavaScript“函数调用”事件监听器

[英]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);
    }
}

As I have stated in a comment in the code I need to be able to listen out to see if addAndRemove is called again whilst in execution. 正如我在代码的注释中所述,我需要能够侦听执行addAndRemove是否再次调用addAndRemove I only want to cancel the existing Ajax request if a new one has been requested. 如果要请求一个新的Ajax请求,我只想取消它。 How can I do this? 我怎样才能做到这一点?

You need to use a closure to create a state in your function. 您需要使用闭包在函数中创建状态。

You could refactor your function this way. 您可以通过这种方式重构您的功能。

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);
    }
  }
}());

that way ajaxRequest will point to the same reference no matter how much time your function is called. 这样,无论您的函数被调用了多少时间,ajaxRequest都将指向相同的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM