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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With