将设置放在JQuery插件中的位置

时间:2012-12-18 22:01:39

标签: jquery jquery-plugins

来自JQuery插件创作文档的Default and Options section,比如包含这样的设置:

(function( $ ){

  $.fn.tooltip = function( options ) {  

    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
      'location'         : 'top',
      'background-color' : 'blue'
    }, options);

    return this.each(function() {        

      // Tooltip plugin code here

    });

  };
})( jQuery );

但更进一步,就像在Data section中一样,构建插件的方式发生了变化,目前尚不清楚如何声明和初始化设置。

他们会像这样被抛入init方法吗?如果是这样,另一种方法如何访问它们?

  var methods = {
    init: function(options) {

      // no idea if this is the right place for settings
      var settings = $.extend({}, $.fn.myPlugin.defaultSettings, options || {});

      return this.each(function() {
       ....
      });
    },
    displaySettings: function() {
      console.log('WTF to do?');
    }
  ...

3 个答案:

答案 0 :(得分:0)

我会看一下这篇文章:jQuery Plugin Design Patterns

所有示例中还有an accompanying Github repository

答案 1 :(得分:0)

这条线可能正是您所寻找的。它检查方法是作为参数传递还是包含选项的对象。

if ( methods[method] ) { //Check if a method was passed
    return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) { // Check if options were passed
    // If Options passed, apply them to the .init method where it accepts arguments. 
    // In the example it doesn't show the init method utilizing the options.
    return methods.init.apply( this, arguments ); 
} else {
    $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
}    

如果选项已通过,那么您将在init方法中使用上面相同的代码:

var methods = {
    init: function(options) {
        var settings = $.extend( {
            'location'         : 'top',
            'background-color' : 'blue'
        }, options);
...

你通常'初始化'一个插件作为你的第一个方法,所以选项就在那里。通常你不会使用'destroy'等方法传递选项。

答案 2 :(得分:0)

这对我有用:

(function ( $ ) {
    var methods = {
        init : function(options) {
            var settings = $.extend({
                some_setting: true
                ,some_other_setting: true
            }, options );

            var _this = this;
            _this[0].pluginNameSettings = settings;
            // rest of your init method here
        } // end of init method
        ,some_method: function( ) {
            $(this)[0].pluginNameSettings.some_setting;
            // rest of your method here
        }
    }

    $.fn.dropDownMenu = function(methodOrOptions) {
        if (methods[methodOrOptions]) {
            return methods[ methodOrOptions ].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions === 'object' || ! methodOrOptions) {
            // Default to "init"
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  methodOrOptions + ' does not exist on jQuery.dropDownMenu');
        }
    };
}( jQuery ));