9

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?

kero
  • 10,647
  • 5
  • 41
  • 51
Kerem
  • 11,377
  • 5
  • 59
  • 58
  • Possible duplicate of [If a DOM Element is removed, are its listeners also removed from memory?](http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory) – Fred Gandt May 01 '17 at 15:09

2 Answers2

13

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

Community
  • 1
  • 1
Anujith
  • 9,370
  • 6
  • 33
  • 48
7

Removing the element from the DOM doesn't (or shouldn't) remove any of its listeners; after all, you may very well just be in the process of re-arranging your DOM elements, and as such you don't want to discard any listeners.

You can remove the listeners before, or after, it shouldn't make any difference.

If your plan is to remove the elements, and no longer use them, it would be wise to proceed with removing the events so as to avoid any possibility of memory leaks.

Sampson
  • 265,109
  • 74
  • 539
  • 565
  • `DOM doesn't (or shouldn't) remove any of its listeners`. I think enough for me. Thanks! – Kerem Dec 26 '12 at 12:24
  • @qeremy What part are you having issues with? – Sampson Dec 26 '12 at 12:25
  • 3
    What about memory leaks? When the node is obviously thrown away, does it matter whether you unbind the event or not? – Rob W Dec 26 '12 at 12:25
  • 1
    It's not entirely clear from this answer whether it's a requirement to remove event handlers or not. Perhaps they're removed implicitly by the browser after it's no longer referenced by any variable? – Ja͢ck Dec 26 '12 at 12:26
  • @JonathanSampson; it's my misunderstand cos of poor English, it's OK. :) – Kerem Dec 26 '12 at 12:28
  • @RobW It's not clear from the question whether the OP is throwing the element(s) away, or simply removing them. – Sampson Dec 26 '12 at 12:28
  • @JonathanSampson Indeed, but *if* the element is discarded, is it beneficial to unbind the event first? – Rob W Dec 26 '12 at 12:30
  • 1
    @RobW If I'm going to null-out a reference, I would probably remove any bound listeners prior to doing so. I don't have any data or citation at the moment to support this - I'm just a paranoid developer who has spent over 10 years wrangling these browsers. – Sampson Dec 26 '12 at 12:32
  • @JonathanSampson; Last appending to your answer is good too! thanks! – Kerem Dec 26 '12 at 12:40