views:

31

answers:

2

I have a UI using dynamic tabs, so content can be loaded into a tab and then the tab can be closed and the content removed from the page.

When I load content into a tab I attach a lot of events to elements using jQuery.

What happens when I remove these elements from the page? Does jQuery need to know?

Also, does it matter if I attach an event multiple times? For example, in my tab load I might attach an event using a class selector like $('.submitButton').click(...). But I might already have other tabs open, which have already had the submitButton event attached. In this case, I'll be re-attaching the same event. Is there any problem with this?

+1  A: 

If you remove an element with .remove() all bound events and jQuery data associated with the element is removed.

Other than .detach(), which will remove the element from the DOM, but keeps all associated data and events in memory (which is useful if you want to re-insert that element at a later time)

jAndy
+2  A: 

If you use jQuery methods .remove() or .empty(), they will clean up all events (and other data) that were assigned with jQuery.

From the docs for remove():

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

and for empty():

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

If you used native API methods of removing, all that data will hang around. So better to use jQuery methods.

patrick dw