views:

32

answers:

1

Here is the problem: I have a very complex plugin that does lots of different initialization and binding when it is executed.

I want to be able to run the same plugin multiple times on the same element, giving it different options. After it runs once on the element, certain initialization does not need to be done again on subsequent executions on that element.

Currently the plugin code is inside of a closure and it doesnt know anything about other times the same plugin has run on the element.

Is there a pattern that people follow when they want inter-communication?

I am thinking of something like this:

$.plugin = {
   globalRefs = [];
}
$.fn.plugin = function() {
  var that = {};
  $.fn.plugin.id ++; //each execution gets its unique id

  var privateFn = function() { ... };

  that.privateFn = privateFn; //expose all useful inner functions to that.

  $.plugin.globalRefs[$.fn.plugin.id] = that; //make that global 
} 
$.fn.plugin.id = 0;
+3  A: 

You talk about "other plugins", but it's not clear what you mean by that; what other plugins? What do they need to "know" about each other?

If you just want to maintain state, why not just use the jQuery data() mechanism to store whatever you need right on the target DOM elements? That would let your plugin find out about previous invocations, and it would also allow these mysterious "other plugins" to use that stored data too.

// ...
$(theElement).data('pluginName', { 'fabulous': 'data' });

The data that you store with this mechanism can be anything you like:

$(theElement).data('pluginName', {
  'aNumber': 23.5,
  'anArray': ['hello', 'world'],
  'aFunction': function(arg) {
    alert("wow a function! Here is the argument: " + arg);
  }
  'anObject': {
    'more': 'stuff'
  }
});
Pointy
updated question to be more clear. as far as .data() - i dont think this will work since i want to pass actual functions around. can i do that with data? i was under the impression that it only allowed strings.
mkoryak
well ok then. thanks
mkoryak