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

1
  • 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. Commented Apr 27, 2017 at 20:45

1 Answer 1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.