james emanon
james emanon

Reputation: 11807

jQuery plugin instances and remove/destroying them?

I have a situation in which a plugin that I have on the page will be references more than a few times. The issue is that the elements that will call the plugin will be created on the fly. And then removed etc... for instance.

  1. I have a div structure and it creates some child elements.

i. I add the plugin instance on these children. They do some magic etc..

ii. User clicks a button, new set of child elements are created -- I create the plugin instances.

NOW -- what happens to those created in point "i" above? I am not using "widget" so I don't have the destroy method.

So, can I just call the child elements, and just loop thru them and destroy the data element etc.. ala.

$.each('[some_class_that_represents_all_elements]', function(a,b){
     $(b).data('PLUGIN_NAME') = null; // or
     delete $(b).data('PLUGIN_NAME'); // or
     $(b).data('PLUGIN_NAME', null);
})

If the elements are removed from the DOM, do the plugin instances also get removed/cleaned up?

Upvotes: 0

Views: 5160

Answers (1)

Mike Edwards
Mike Edwards

Reputation: 3771

jQuery by default will cleanup any data you store using $(el).data() when you call the $(el).remove() method.

If you use $(el).detach() the data is preserved.

http://api.jquery.com/jQuery.data/

jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page.

Upvotes: 2

Related Questions