views:

61

answers:

2

Hi,

Is it possible to remove all event listeners of an element and its children? Something like:

myElem.removeEventListeners();

I need this because I have a complex element with events, and I need to create a copy of it -- like a static image that does not react to any events.

A: 

I do not know of one, and a search on Google didn't yield any obvious results. One easy, kludgy solution is to create a function that cycles through every event and sets it to null, such as

function removeEvents(obj)
{
    obj.onblur = null;
    obj.onchange = null;
    obj.onclick = null;
    // ...
}

Call this function as follows: removeEvents(myElem). A complete list of JavaScript event handlers can be found at http://www.elated.com/articles/events-and-event-handlers/.

Undoubtedly there is a more elegant way to write this function, but I don't know if there is a more elegant way to solve this problem. It would be lovely if someone knows of one. If you are binding events through a JavaScript library, such as jQuery, there may be other, better options.

TNi
I'd set it to an empty function (`function () {}`) instead in case it still gets called.
Casey Hope
Depending on the browser, elements with no event handler have it set to either undefined or null. I don't think setting it to null presents any problems, but if so your suggestion should be taken.
TNi
+1  A: 

If you use cloneNode, the event listeners won't be copied.

If you want a robust solution your best bet is probably to write a wrapper to attach/detach listeners, and keep track of them yourself. Something like Dean Edwards' addEvent.

galambalazs
Thanks for the tips. I am using W3C event listeners, so, I probably have to write a wrapper, which I would like to avoid...
rFactor
but if you use `cloneNode` your listeners won't be copied. See my update,
galambalazs