Alana Storm
Alana Storm

Reputation: 166156

Removing DOM Event Observer

I'm working in a javascript based system with some legacy code (ominous music), and this legacy code adds event listeners like this

foo.addEventListener("click",function(){
    //do some stuff
});

Is there a way for me to programmatically remove event listeners that have been added like this? I know about removeEventListener, but's it's not clear from the documentation how (if at all) to remove a listener which a programmer added via an anonymous function.

Upvotes: 0

Views: 1580

Answers (3)

Steen
Steen

Reputation: 2887

If you want to get rid of all eventlisteners before adding your own you can use clonenode and remove original. The copy will not have the eventlisteners copied with it.

  var fee = foo.cloneNode();
  foo.parentNode.replaceChild(fee, foo);

Should look the same but without eventlistener.

Got a fiddle here that proves my point: http://jsfiddle.net/U7w7M/1/

Notice how the formatting stays, the position is the same, but click action is removed after first click

Upvotes: 1

Mingle
Mingle

Reputation: 836

You can remove them the same way that you add them by passing in the handler that you created it with. The handler ceases to be an anonymous function at this point though:

var handler = function() {
  // do some stuff
};

foo.addEventListener("click", handler);
foo.removeEventListener("click", handler);

You can do some funky stuff like this to remove handlers with anonymous functions although I don't recommend it, but it is possible and you can't access callee in strict mode:

document.addEventListener('click', function(e) {
    console.log('click');

    if(e.unbind) {
        document.removeEventListener('click', arguments.callee);
    }
});

var event;

// First actual real event
event = new Event('click');
document.dispatchEvent(event);

// Unbinding event
event = new Event('click');
event.unbind = true;
document.dispatchEvent(event);

// Should not fire
event = new Event('click');
document.dispatchEvent(event);

Upvotes: 1

jfriend00
jfriend00

Reputation: 707996

As far as I can tell, you can't use an anonymous function if you want to call removeEventListener because you need a reference to the same function that you used with addEventListener and the only way to do that is to have a name for the function (e.g. not anonymous).

Similar question and conclusion here: removeEventListener on anonymous functions in JavaScript


Without changing the structure of your code, you can give it a name and then use that name later.

foo.addEventListener("click", function fooClickHandler(){
    //do some stuff
});

// then later
foo.removeEventListener("click", fooClickHandler);

Upvotes: 2

Related Questions