Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I remove event handlers from element before removeChild?

Say, I have an element as <img id="foo" /> and attached some events, e.g click (not inline onclick!).

// somewhere i wrote
foo.addEventListener("click", clickHandler, false);
...
// somewhere i will write
foo.parentNode.removeChild(foo);

Do I need to remove all events too?

like image 636
K-Gun Avatar asked Dec 26 '12 12:12

K-Gun


People also ask

Should I remove event listeners before removing elements?

Removing the event listener first always results in lower memory usage (no leaks).

When should event listeners be removed?

TLDR; Always remove event listeners when you don't plan on using them any longer.

Why should you remove event listeners once they are no longer used?

The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

Can event handlers be removed?

Clear the handlerTo remove an event handler, you can't just delete handler code that is in the form's code-behind file, it's still referenced by the event.


1 Answers

The documentation on jQuery's empty() method says:

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

So: 1) if we didn't remove event handlers explicitly, We'd get memory leaks, and 2) By using empty(), We can avoid this memory leaks.

Also See this do-events-handlers-on-a-dom-node-get-deleted-with-the-node

like image 152
Anujith Avatar answered Oct 07 '22 00:10

Anujith