Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing jQuery plugin -- multiple instantiation

I have a question regarding the local variables for my jQuery plugin. I am pretty sure if I declare them outside the main jQuery function register, then every time the plugin is called it will redefine the variables.

Example:

(function($){
    jQuery.fn.test = function(options){
        if ( options ) { 
            $.extend( settings, options );
          }
        this.each(function(i,item){
            // do whatever i am going to do
        });

    };


    var settings = {
        value1: "hello",
        value2: "word"
    };
})(jQuery);

Say that $(object).test({value1:'newterm'}); is called multiple times.. Am I correct in thinking that every time that method is called, that it will override the settings with the most recently declared settings?

If i want multiple instances of my plugin, do I need to declare everything within the scope of the main jQuery.fn.test = function(){//here} method?

like image 650
Atticus Avatar asked Sep 10 '26 22:09

Atticus


2 Answers

Yes, that is correct, because $.extend will modify settings which is in the closure scope exposed when the jQuery initialization function sets up .test on the global object jQuery. That closure scope is the same everytime you execute .test; therefore, all objects will retain changes.

like image 97
Ryan Avatar answered Sep 12 '26 12:09

Ryan


It depends on the order you pass objects to $.extend. The first (target) object passed will be modified, in your case the settings object. If you want to keep the defaults:

$.extend(options, settings);

Or to get a brand new object:

var newoptions = $.extend({}, options, settings);
like image 38
Daff Avatar answered Sep 12 '26 12:09

Daff