简体   繁体   中英

Removing event listener when using inline anonymous function

In a simple game-app, I'm trying to pass the anonymous event-callback function some arguments. I could only do it using an anonymous function since it fits into the context (its scope identifies the arguments). The problem is that the game has an option to restart. After restarting, it adds to the same nodes new event Listeners, and here as you may guess the old event-listeners are still there, which results in an improper functionality and overloaded app. The solution I could think of is to "refresh" by removing the old eventListeners before adding the new ones. But I could not find any way considering the event-callback function is anonymous!

So, what could be an alternative solution?

var adder = function(colorBox, num){
    colorBox.addEventListener('click', function(){
        eventCall(this, num);
    });
}

var eventCall = function(t, num){
        var clickedBox = t.style.backgroundColor;
....

You can store the function somewhere, so you can reference it later when removing. Using an array, you can store multiple event handlers without them being overwritten by several calls to the adder function, and then have a function that removes all of them etc, something like :

function eventCall(t, num) {
  var clickedBox = t.style.backgroundColor;
}

var fns = [];

function adder(colorBox, num) {
  function fn() {
    eventCall(this, num);
  }

  colorBox.addEventListener('click', fn);

  fns.push(fn);
}

function remover(colorBox) {
  fns.forEach(function(fn) {
    colorBox.removeEventListener('click', fn);
  });
}

You can remove your event handlers via jQuery by using the off function ( http://api.jquery.com/off/ ). For example

$( "p" ).off();

removes all event handlers from all paragraphs. So if you classify all your dom elements with a specific class, it is still possible.

You can remove all event listeners on an element by using the outerHTML property.

colorBox.outerHTML = colorBox.outerHTML;

Setting the outerHTML property to itself will remove any attached event listeners and allow you to start fresh with any new listeners you want to attach.

More information on this method can be found here:

https://stackoverflow.com/a/32809957/5463636

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