How to remove an event of an element declared by an anonymous function?

code example:

element.addEventListener('click',function () { this.style.backgroundColor = '#cc0000' //after element was clicked once what to do here to remove this event ? },false) 

And where to do it, is it possible directly in the function where I put the comment?

+4
source share
2 answers

If you add an event with addEventListener() , you must have a link to this function in order to be able to delete it later.

With an anonymous function, which is only possible with arguments.callee , and then only while you are inside the function itself:

 element.addEventListener('click', function() { this.style.backgroundColor = '#cc0000'; this.removeEventListener('click', arguments.callee); }, false); 

but note that this is not legal in ES5 "strict mode".

Therefore, it would be better to give your callback a name and then use it in the removeEventLister() call:

 element.addEventListener('click', function cb() { this.style.backgroundColor = '#cc0000'; this.removeEventListener('click', cb); }, false); 

Demo at http://jsfiddle.net/alnitak/RsaVE/

+7
source

Not quite anonymous, but here is the best I can come up with (using closure):

 (function(){ var handler = function(){ this.style.backgroundColor = '#cc0000' element.removeEventListener('click', handler, false); }; element.addEventListener('click', handler, false); })(); 

Edit: +1 for Alnitak's revised answer is a little more concise than this.

+2
source

Source: https://habr.com/ru/post/1388621/


All Articles