Just a simple one. Is there any real reason why a callback is required for removeEventListener? Am I supposed to be doing something with it?
example: myView.removeEventListener('click'); wont work, it gives an index beyond bounds error.
neither will myView.removeEventListener('click', false);
the only way is like this: myView.removeEventListener('click', function(){} );
2 Answers
Accepted Answer
Neither way you mention works.
To remove event listener you need pass function reference or event listener id to "removeEventListener" function.
If you add anonymous function, like this:
myView.addEventListener('click', function() {} );you can't remove that event listener because you don't have function reference. Because of that, you need to store it to some variable:
var eventListener = function() {}; myView.addEventListener('click', eventListener); //now you can remove it myView.removeEventListener('click', eventListener);You need function reference because events can have multiple event listeners attached and that's the only way you can distinguish different event listeners attached for same event. Documentation is misleading, "callback" is not callback in right sense of that word, "callback" in documentation should be function reference passed to the "addEventListener" function.
Other way is to store event listener id. I'm not sure how this is done, this is not mentioned in the docs(!), but it can be found in JIRA (search if you're interested).
I think this is how it's done:
var eventId = myView.addEventListener('click', function() {} ); //removing myView.removeEventListener('click', eventId); //or this myView.removeEventListener(eventId);
When you add event listeners, it is often good practice to pass a named function to the addEventListener method rather than an anonymous function. The remove method simply allows you to pass that same function to be removed. Check the MDN Docs Page for more info on that.
Your Answer
Think you can help? Login to answer this question!