JQuery - plugin options default extend ()

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?

+6
source share
2 answers

You mixed the order of the arguments in $.extend (the goal should be first), it should be:

 settings = $.extend(settings, options); 

See this script and docs for $.extend()

To avoid confusion, you can also expand your default settings as follows:

 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 }; 
+19
source

You are overwriting your default values. Try creating a new variable to save the settings in 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; } }; 
+4
source

Source: https://habr.com/ru/post/912322/


All Articles