views:

170

answers:

3

Is there anyway to remove an event listener added like this:

element.addEventListener(event, function(){/* do work here */}, false);

without replacing the element?

A: 

Assigning event handlers with literal functions is tricky- not only is there no way to remove them, without cloning the node and replacing it with the clone- you also can inadvertantly assign the same handler multiple times, which can't happen if you use a reference to a handler. Two functions are always treated as two different objects, even if they are character identical.

kennebec
"You can't" in summary? which is what I think is the correct answer.
Erik Vold
You can, if you assign them as properties, and not using addEventListener.element.onmouseover=function(){dothis};element.onmouseover='';
kennebec
@kennebec: In Greasemonkey applications, we don't have any control over how events are created in the base page. FYI, in a GM script, something like `element.onmouseover=function` won't work anyway, because of sandbox protection. See http://commons.oreilly.com/wiki/index.php/Greasemonkey_Hacks/Getting_Started#Pitfall_.232:_Event_Handlers .
Brock Adams
+1  A: 

You could remove the event listener like this:

element.addEventListener("click", function() {
    element.removeEventListener("click", arguments.callee, false);
}, false);
icktoofay
That only works if you are adding the event listener in the first place -- that you can modify the original listener() code. Since this is a Greasemonkey application, that is not possible. Even if the base-page script was changed, you'd only be adding *another* anonymous listener.
Brock Adams
@Brock: Oh, I thought the intention was to remove a listener you added. I don't know of any way to remove a listener you didn't add and have no reference to the function of.
icktoofay
Brock is correct, this is a question for user scripting, but good answer none the less, I gave it an up vote!
Erik Vold
A: 

There is no way to cleanly remove an event handler unless you stored a reference to the event handler at creation.

Joe