Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Example code:

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 function where I put the comment?

like image 350
rsk82 Avatar asked Jan 18 '23 22:01

rsk82


2 Answers

If you add an event with addEventListener() you must have a reference to that function available to be able to subsequently remove it.

With an anonymous function that's only possible with arguments.callee, and then only while you're within the function itself:

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

but note that this isn't legal in ES5 "strict mode".

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

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

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

like image 108
Alnitak Avatar answered Apr 27 '23 01:04

Alnitak


Not truly anonymous anymore, but here is the best I can come up with (using a 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 - it's a little more concise than this one.

like image 38
ziesemer Avatar answered Apr 27 '23 01:04

ziesemer