JQuery: a cross-board plugin
Here's the problem: I have a very complex plugin that does a lot of different initialization and bindings when it is executed.
I want to be able to run the same plugin multiple times on the same element by giving it different options. Once it runs once on an element, some initialization does not need to be repeated on subsequent executions of that element.
Currently, the plugin code is inside the closure and it knows nothing about other times when the same plugin fires an element.
Is there a pattern that people follow when they want to communicate?
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;
a source to share
You are talking about "other plugins" but it is not clear what you mean by that; what other plugins? What do they need to "know" about each other?
If you just want to store state, why not just use jQuery's engine data()
to store what you need right on the target DOM elements? This will let your plugin know about previous calls, and also allow those cryptic "other plugins" to use that saved data.
// ...
$(theElement).data('pluginName', { 'fabulous': 'data' });
The data you store using 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'
}
});
a source to share