views:

413

answers:

2

I am working with a jquery plugin that looks like this:

(function($){
    var options;
    $.fn.main(opts){
     options = opts;
     //rest of code
    }
    $.fn.otherFunc(){
     //does something with options
    }
}(jQuery));

The problem here is that if i use this plugin 5 times on the page, the options variable gets overwritten, and so all 5 instances share those options. This is bad, i want each plugin instance to have its own config.

Is there a non-hackish jQuery way to accomplish this?

edit:

I should add that i would consider addition options to $(this) in $.fn.main as an expando somewhat hackish, because $.fn.otherFunc might not be called on the $(this) from the main function, so i wouldnt have access to my stuff!

+1  A: 

If you're applying the same plugin to several elements like this

$("#div1, #div2, #div3, #div4, #div5").main(opts);

You should split it in 5 different calls with different options - i.e.:

var opts1 = {...};
$("#div1").main(opts1);

var opts2 = {...};
$("#div2").main(opts2);

// etc.

Also, add a paraemter to $.fn.otherFunc to receive which options object it should work on.

EDIT: if you're not calling otherFunc from inside main(), you should consider why you're sharing options between them. In that case, if you post what's your original problem (i.e. real world problem you're trying to solve) we might be able to offer a better solution than having two different plugins sharing options instead of merging them into just one.

Seb
+1  A: 

The code given in your example had syntax errors, I'm guessing that this will work better:

(function($){
    var options;
    $.fn.main = function(opts){
        options = opts;
        //rest of code
        alert(options.text);
    }
    $.fn.otherFunc = function(){
        //does something with options
    }
})(jQuery);

$('a:first').main({text:'txt'});
$('a:last').main({text:'some other text'});

In your code, I would recommend adding the options data to the DOM element itself to keep track of the options, after all, that's where the "behavior" is being directed at, so it's natural to keep it there, not in a separate object.

altCognito