1

I have an app where the user can create and destroy graphical objects. Each one of these objects spawns multiple event listeners. When the object is destroyed (removed from the DOM), do I have to remove all of those event listeners? What could happen if I don't?

The event listeners in this case are mousedown and mouseup on the object itself, and mousemove on the document body, but what's best practice in the general case.

Jack M
  • 4,769
  • 6
  • 43
  • 67

3 Answers3

0

If the object is removed from the DOM, and you don't have any references to it in live Javascript variables, the object will be garbage collected, and any event handlers associated with it will be discarded as well. You don't need to explicitly clear the handlers first.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Worst case scenario - your events are still being triggered somehow and your code is hogging a lot of unnecessary resources.

If you are truly removing the elements from the DOM, then it might not matter but it could still potentially cause memory leaks depending on the scope and closure of your code.

If it isn't hard, removing them is nice. I wouldn't say it is required.

lemieuxster
  • 1,081
  • 7
  • 14
0

In modern browsers (chrome/firefox/webkit) it doesn't matter - when DOM elements are disposed, so are the event handlers tied to them, since both are handled by the same memory manager.

The same goes for IE9 and up.

For IE8 and IE7 however, there is separate memory managers for DOM and jScript, which means that unless you unbind the events and null the event handlers before disposing the DOM elements, no memory will be released.

You can read more about memory leaks in IE versions here:

http://javascript.crockford.com/memory/leak.html

http://blog.j15r.com/blog/2009/07/12/Memory_Leaks_in_IE8

http://msdn.microsoft.com/en-us/library/bb250448(v=vs.85).aspx

http://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68