1

So I have a set of jQuery plugins, really basic stuff, but I split the code into plugins because I don't like having a huge jQuery(document).ready() function where I store the entire application logic.

Each plugin has a "destructor", which is basically a function that I defined in the plugin prototype object. This function unbinds events used by the plugin, removes DOM elements that were added by the plugin etc.

Plugins are initialized like this:

$('.element').plugin();

Is there any way I can get all the elements that have my plugins attached to them, from another plugin which is supposed to replace the body HTML, so I can call the destructor function?

I was thinking to store each plugin instance inside a global array, then I can access that array from any plugin. But maybe there is a better way that doesn't use the global state?

Alex
  • 66,732
  • 177
  • 439
  • 641
  • When I build jquery widgets I use a [custom template that I wrote](https://github.com/zzzzBov/jQuery-widget.tmpl.js/blob/master/jqwt/jquery-widget.tmpl.js). It includes extending `$.expr[':']` so that the instantiated widgets can be selected. – zzzzBov Nov 29 '13 at 00:43

2 Answers2

1

I don't think there is a ready made method for it... but as a hack you can add a class to the target elements in your plugin and then use that class to get all elements with the widget initialized lke

$.fn.plugin = function(){
    this.addClass('my-plugin-class');
}

then to initialize

$(element).plugin()

to get all elements with the plugin

$('.my-plugin-class')....

But if it is a jQuery UI widget then you can use the selector $(':ui-widgetname'), see this answer

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • That's actually a good idea, I could then select and destroy plugins that are hooked on elements from a certain area of the page, like `#main .plugin` – Alex Nov 29 '13 at 01:02
1

Arun P Johny wrote the rigth idea -- just delete 'footprint' of your job by marking the affected DOM elements with some specific class name.

I want just add an idea. Plugins are the methods of the library and nothing more. If you need the destroyer for constructor -- just make another plugin for it:

$.fn.overture = function (){...};// construct
$.fn.crescendo = function (){...};// more construct
$.fn.quietFarewell = function (){...};// destructor for everything above

$(...).overture().crescendo().quietFarewell(); 
Community
  • 1
  • 1
Ruben Kazumov
  • 3,803
  • 2
  • 26
  • 39