RemoveEventListener not working

I don’t know what I am doing wrong, but here is an example of what I am doing and it does not work.

someDom.addEventListener('mousemove',function(ev) {self.onInputMove(ev)},false); someDom.removeEventListener('mousemove',self.onInputMove); 

The removeEventListener code executes, but it just does not remove the mousemove listener

+7
source share
4 answers

removeEventListener removes a listener that exactly matches the added function.

In this case, the function added by addEventListener was:

 var some_func = function(ev) { self.onInputMove(ev); }; 

Keep a link to the actual function and you will be good. So, for example, the following should work:

 someDom.addEventListener('mousemove',self.onInputMove,false); someDom.removeEventListener('mousemove',self.onInputMove,false); 
+25
source

onInputMove not a callback method. So you need to do something like:

 var event = function(ev) {self.onInputMove(ev)}; someDom.addEventListener('mousemove', event,false); someDom.removeEventListener('mousemove', event, false); 
+5
source

Why do it yourself, just use the following to bind an event to an element:

 element.onmousemove = function(e) { // Some code here... alert("Mouse moved!"); }; 

Now that you want to delete the event, simply do the following:

 element.onmousemove = null; 

Done!

Hope this helps you guys!

+1
source

This page comes first in finding this / such issue on Google. Therefore, in addition to the answers already mentioned, here is another interesting fact for the future:

Leaving the third optional variable in addEventListener () for useCapture / useBubble (false by default) creates some problem when deleting the same eventlistener with the same callback name. I ran into this problem while working on chrome. I can not say about other browsers.

So mention the third variable explicitly as "false".

+1
source

All Articles