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?
Removing the event listener first always results in lower memory usage (no leaks).
TLDR; Always remove event listeners when you don't plan on using them any longer.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With