Shannon Hochkins
Shannon Hochkins

Reputation: 12186

Jquery plugin allow multiple instances

I'm using the jQuery boilerplate template for a plugin I'm writing. It basically just runs an ajax call and replaces the content of the element it has running on. Example:

My plugin name is 'getContent'

$('.container').getContent({
    html : 'foo'
});

Very simplified version of the plugin, however right at the very bottom of the template there is this:

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations

$.fn[pluginName] = function(options) {
    this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
            $.data(this, "plugin_" + pluginName, new Plugin(this, options));
        }
    });

    // chain jQuery functions
    return this;
};

Obviously it does some checks to see if the pluginName is already bound to the element. In this case it is, and the plugin doesn't run when you try to do it again later on in the same page instance.

Is the correct way to fix my issue to literally just remove the if around the new Plugin section?

Upvotes: 0

Views: 2063

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

in order to be able to able to run the plugin for multiple instances you need to have a new closure for each instance, try the code below:

function getContentFunc(elem,options){
    //things you want your plugin to do
};

$.fn[pluginName] = function(options) {
    if ($.data(this, "plugin_" + pluginName)) return;
    return $(this).each(function() {
        getContentFunc(this,options);
        $.data(this, "plugin_" + pluginName);
    });
};

see a very simple plugin, done with the same method HERE

Upvotes: 0

Related Questions