Following the good jQuery Plugins/Authoring instructions I have a little question
(function($){
// Default Settings
var settings = {
var1: 50
, var2: 100
};
var methods = {
init : function (options) {
console.log(settings);
settings = $.extend(options, settings); // Overwrite settings
console.log(settings);
return this;
}
, other_func: function () {
return this;
}
};
$.fn.my_plugin = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.my_plugin');
}
};
})(jQuery);
If I do
>>> $('my_element').my_plugin({var3: 60})
Before Object { var2=100, var1=50}
After Object { var3=60, var2=100, var1=50}
[ my_element ]
>>> $('my_element').my_plugin({var1: 60})
Before Object { var1=50, var2=100}
After Object { var1=50, var2=100}
[ my_element ]
Why is my var1
not overridden ?
You mixed up the order of the arguments in your $.extend
(target should be first), it should be:
settings = $.extend(settings, options);
See this fiddle and the docs for $.extend()
To avoid confusion you can also extend your settings with your defaults like this:
methods.init = function(options){
var settings = $.extend({
key1: 'default value for key 1',
key2: 'default value for key 2'
}, options); // <- if no / undefined options are passed extend will simply return the defaults
//here goes the rest
};
You are overwriting your defaults. Try creating a new variable to store the settings within the init method.
var defaults = {
var1: 50
, var2: 100
};
var methods = {
init : function (options) {
console.log(defaults);
var settings = $.extend({},defaults,options || {});
console.log(settings);
$(this).data("myPluginSettings",settings);
return this;
}
, other_func: function () {
console.log(this.data("myPluginSettings"));
return this;
}
};
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