jQuery-插件选项默认扩展()

jQuery - plugin options default extend()

本文关键字:扩展 默认 插件 选项 jQuery-      更新时间:2023-09-26

按照良好的jQuery插件/编写说明,我对有一个小问题

(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没有被覆盖?

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

settings = $.extend(settings, options);

参见此小提琴$.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
};

您正在覆盖默认值。尝试在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;
    }
  };