0

I have a canvas element in which I draw something using WebGL.
Depending on what is drawn I am adding an event listener.

Now when I am redrawing the canvas, I want to remove the old event listener and add a new one.

Simply doing this will not work:

canvas.removeEventListener("click", function(event){ 
                                        colorbarClicked(event, viewdata); 
                                    }, false);
canvas.addEventListener("click", function(event){ 
                                      colorbarClicked(event, viewdata); 
                                 }, false);

I think it is because the colorbarClicked function has already changed (maybe because its parameters have different values?) and not matching the old one which I want to remove any more.

So my problem is that each time I am redrawing event listeners get added and therefore doubled. But the colorbarClicked function depends on what is drawn in the canvas, so I definitely need to change it.

Shaeldon
  • 873
  • 4
  • 18
  • 28
phen
  • 119
  • 2
  • 8
  • possible duplicate of [JavaScript: remove event listener](http://stackoverflow.com/questions/4402287/javascript-remove-event-listener) – James Donnelly Oct 29 '14 at 14:41

2 Answers2

3

You need to remember the function you used when adding, and use that same function again when removing:

// Somewhere *outside* the code doing the adding/removing (in containing code)
var listener = null;

// In the code adding/removing
if (listener) {
    canvas.removeEventListener("click", listener, false);
}
listener = function(event){ colorbarClicked(event, viewdata); };
canvas.addEventListener("click", listener, false);

Side note: Adding and removing a handler every time seems awkward. Normally, you'd want to just add the handler the once, and have it respond to whatever changes you make.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You can use named functions. Take the example below:

function foo(){
  alert("this comes only once");
  this.removeEventListener('click', foo);
}
dude.addEventListener('click', foo);
<button id="dude">Click Me</button>

What is happening here is that the function foo is defined in the global scope. It has a unique identity of it's own. What the function basically does is that it creates an alert, and then removes itself from the click event for the button. So when you click it, the listener is removed, and thus, you no longer see it.

Your code doesn't work as intended because the function you pass as callback to addEventListener has no unique identity, and Javascript doesn't know what to remove.

This method also prevents things like callback hell :)

user3459110
  • 6,961
  • 3
  • 26
  • 34