1

I added an event listener like so:

 function position(key){
     canvas.addEventListener("mousemove", function(evt){
     var mousePos = getMousePos(canvas, evt);
     document.getElementById("demox["+key+"]").value =mousePos.x;
     document.getElementById("demoy["+key+"]").value =mousePos.y;
     }, true);
 }

I'm trying to remove this event listener but I couldn't because I'm using the function argument key in the callback function of the event listener, I tried this but it didn't work :

 function myFunction(evt){
     var mousePos = getMousePos(canvas, evt);
     document.getElementById("demox["+key+"]").value =mousePos.x;
     document.getElementById("demoy["+key+"]").value =mousePos.y;
 }
 canvas.removeEventListener('mousemove', myFunction, true);

What should I do to remove the 'mousemove' event listener

Berzerkfar
  • 45
  • 5
  • you can only remove named functions. so unless you add it `canvas.addEventListener("mousemove", myFunction)` you won't be able to remove it with removeEventListener. – rlemon Apr 27 '17 at 20:45

1 Answers1

0

The reason you are not able to remove the event listener is not because of the key parameter, per se. It is because the mousemove event handler is an anonymous function. If the function being registered is anonymous, it can never be unregistered from outside of itself because it has no identifier for you to reference it by.

You need to change to using a named function declaration, so that you can properly reference the function later and have the key variable available via a higher scoped variable:

 var key = null;

 function position(val){
     key = val;
     canvas.addEventListener("mousemove", mouseHandler , true);
 }

 function mouseHandler (evt){
     var mousePos = getMousePos(canvas, evt);
     document.getElementById("demox[" + key + "]").value =mousePos.x;
     document.getElementById("demoy[" + key + "]").value =mousePos.y;
 }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71