I see that the event handlers registered through .on() are held in $.cache.
I also see that the event handlers are also held in $(elem).data().
The objects held in $.cache refer to the DOM nodes on which the events are registered. This leads to memory leak when the DOM nodes are detached, and this makes .off() calls mandatory.
I have a situation where I don’t know when the DOM node (to which I attached the event handler) is being detached. While I can hold the reference to that DOM node in my code and call .off() to clean up, it doesn’t seem nice, because it is not straightforward to know when the DOM node is being removed.
What is the best way to do this?
If you’re going to use jQuery, you must use its API for removing elements, and you must use the proper methods, otherwise, as you stated, you’ll have memory leaks.
If you don’t know when the DOM node is being removed, and if it is causing a leak, I’d assume this means that you are using another library alongside jQuery. That’s just not a good idea for this very reason.
You need to ensure that any elements affected by jQuery are removed by jQuery. There’s also some data stored in
$.cachethat you didn’t explicitly set. This means that all elements should be removed with jQuery, instead of just those that you think may have data.To associate handlers and other data with elements. The link between the data and the elements is basically a serial number stored on an expando property on the element.
If you remove the element without jQuery, the associated data in
$.cacheis orphaned.The purpose of this approach was to prevent potential leaks. Unfortunately it potentially creates more severe leaks.