If I use jQuery’s live or delegate functions to create event handlers for future elements that will be inserted into the DOM do I need to do anything prior to removing those elements from the DOM so no type of memory leak occurs?
THe elements will likely be added/removed via jQuery’s template plugin if that makes a difference.
I haven’t found any confirmation about this and wanted to be sure. Thanks!
No. Consider the way
live()works:There’s a single event handler function attached to the DOM for all
live()handlers – no matter how many handlers you attach vialive()or how many elements a single handler might conceivably match.This function is responsible for determining whether an event which has bubbled up the DOM originated from an element matching a selector previously registered by calling
live().Because no event handlers are actually attached to the DOM elements matching the selector provided to
live(), there can be no memory leak if those elements are removed.Keep in mind jQuery handles the necessary clean-up of bound event handlers when you use jQuery to remove elements. The only way you’ll leak is if you blast away elements by setting
innerHTMLon a container.