jQuery - 插件选项默认extend()

时间:2012-04-03 14:30:31

标签: javascript jquery jquery-plugins

遵循良好的jQuery Plugins/Authoring说明,我有一个小问题

(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);

如果我这样做

>>> $('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 ]

为什么我的var1没有被覆盖?

2 个答案:

答案 0 :(得分:20)

你混淆了$.extend中的参数顺序(目标应该是第一个),它应该是:

settings = $.extend(settings, options);

参见 this fiddle docs for $.extend()

为避免混淆,您还可以使用以下默认设置扩展您的设置:

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

};

答案 1 :(得分:4)

您正在覆盖默认设置。尝试创建一个新变量来存储init方法中的设置。

  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;
    }
  };