Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 812
Pierre de LESPINAY Avatar asked Apr 03 '12 14:04

Pierre de LESPINAY


2 Answers

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

};
like image 65
m90 Avatar answered Nov 18 '22 10:11

m90


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;
    }
  };
like image 24
Kevin B Avatar answered Nov 18 '22 08:11

Kevin B