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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9995392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:26:41  来源:igfitidea点击:

jQuery - plugin options default extend()

javascriptjqueryjquery-plugins

提问by Pierre de LESPINAY

Following the good jQuery Plugins/Authoringinstructions I have a little question

按照良好的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);

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 var1not overridden ?

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

回答by m90

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

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

settings = $.extend(settings, options);

See this fiddleand the docs for $.extend()

请参阅此小提琴文档$.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

};

回答by Kevin B

You are overwriting your defaults. Try creating a new variable to store the settings within the init method.

您正在覆盖默认设置。尝试创建一个新变量来存储 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;
    }
  };