2

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;
....
2
  • Look at this workaround to remove the event listener from colorBox - stackoverflow.com/questions/19469881/… Commented May 10, 2017 at 18:23
  • I tried it.., I do guess it has some downsides.., which makes it not helpful at all. Commented May 10, 2017 at 18:26

3 Answers 3

3

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);
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for helping me out.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.