开发者

Will removing elements with jquery live events cause a memory leak?

开发者 https://www.devze.com 2023-04-04 15:06 出处:网络
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 开发者_StackOver

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 开发者_StackOverflow中文版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:

The handler passed to .live() is never bound to an element; instead, .live() binds a special handler to the root of the DOM tree.

There's a single event handler function attached to the DOM for all live() handlers – no matter how many handlers you attach via live() 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 innerHTML on a container.


Whilst I cannot confirm it totally, I'd be very surprised if this caused a memory leak.

I think the way Live works is that it attaches to the document and then scans the document for matches on the event.

Pretty sure it doesn't attach events to elements created at runtime the way $(".element").click does.

0

精彩评论

暂无评论...
验证码 换一张
取 消