rsk82
rsk82

Reputation: 29387

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?

Upvotes: 4

Views: 161

Answers (2)

ziesemer
ziesemer

Reputation: 28697

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.

Upvotes: 2

Alnitak
Alnitak

Reputation: 339816

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/

Upvotes: 7

Related Questions