Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: removing an anonymous event listener [duplicate]

Possible Duplicate:
Removing an anonymous event listener

I have the following cross browser function to add an event listener:

_SU3.addEventListener = function(elem, eventName, fn) {
if(elem.addEventListener ) {
    elem.addEventListener(eventName, fn, false);
  } else if (elem.attachEvent) {
      elem.attachEvent('on'+eventName, fn);
  } 
};

I'm adding the listener like this:

_SU3.addEventListener(_show, "click", function(event) { 
                             _SU3.getChildren(_show, uri, element); 
                    });

Which is all fine. However I want to remove the listener after it has been called once. I.e something like:

_SU3.getChildren = function(_show, url, element) {

... blah... 

_SU3.removeEventListener(_show, 'click', ANON_FUNCTION);

};

But of course the listener function is anonymous so there's no function name to reference.

How can I remove the listener?

Thanks

like image 595
Richard H Avatar asked Jan 06 '11 15:01

Richard H


3 Answers

You need to keep a reference to the function:

var foo = function(event) { _SU3.getChildren(_show, uri, element); };

_SU3.addEventListener(_show, "click",  foo);

...

_SU3.getChildren = function(_show, url, element) {

... blah... 

_SU3.removeEventListener(_show, 'click', foo);

};

Make sure that the variable foo is in the scope of where you remove the event listener.

like image 194
Matt Avatar answered Oct 17 '22 10:10

Matt


You can't. If you want to remove it, you have to store a reference to it. How else would you be able to distinguish it from the others?

like image 24
Ivo Wetzel Avatar answered Oct 17 '22 10:10

Ivo Wetzel


Instead of removing the event listener, arrange for it to keep track of whether it's been called:

addOneShotListener = function(elem, eventName, fn) {
  var triggered = false, handler = function(ev) {
    if (triggered) return;
    fn(ev);
    triggered = true;
  };

  if(elem.addEventListener ) {
    elem.addEventListener(eventName, handler, false);
  } else if (elem.attachEvent) {
    elem.attachEvent('on'+eventName, handler);
  } 
};

That variation on your original function just wraps the original handler (the "fn" passed in) with a function that only calls the handler the first time it is invoked. After that, it sets a flag and won't ever call the original handler function again.

like image 24
Pointy Avatar answered Oct 17 '22 11:10

Pointy