简体   繁体   中英

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. I only want to cancel the existing Ajax request if a new one has been requested. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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