jskidd3
jskidd3

Reputation: 4783

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?

Upvotes: 2

Views: 75

Answers (1)

mpm
mpm

Reputation: 20155

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.

Upvotes: 3

Related Questions