4

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rsk82
  • 28,217
  • 50
  • 150
  • 240
  • Related question on getting a list of event listeners: http://stackoverflow.com/questions/7810534/have-any-browsers-implemented-the-dom3-eventlistenerlist/7814692#7814692 – user123444555621 Dec 30 '11 at 15:46

2 Answers2

7

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/

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • But I wonder if they would really delete `arguments.callee` functionality from the browsers, it can be deprecated for tens of years and work like a charm. – rsk82 Dec 30 '11 at 14:58
  • 1
    @rsk82 it's already deleted if the code declares `"use strict";` – Alnitak Dec 30 '11 at 14:59
2

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.

ziesemer
  • 27,712
  • 8
  • 86
  • 94