1

jQuery 文档建议为插件设置默认值,并允许用户发送任何自定义值。为此,用户使用 将自定义值作为对象传递$.fn.tooltip = function( options ) {}。我感觉合理。

然后在同一篇文章的后面,他们建议将插件的所有方法收集在一个称为方法的对象文字中,并通过传递方法的字符串名称来调用给定的方法,例如$.fn.tooltip = function( method ) {}.

那么,我要发送选项或方法$.fn.tooltip = function( ? ) {}吗?

另外,为什么方法对象是在插件之外声明的?

来源:http ://docs.jquery.com/Plugins/Authoring#Defaults_and_Options

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

来源:http ://docs.jquery.com/Plugins/Authoring#Plugin_Methods

(function( $ ){

  var methods = {
    init : function( options ) { 
      // THIS 
    },
    show : function( ) {
      // IS
    },
    hide : function( ) { 
      // GOOD
    },
    update : function( content ) { 
      // !!! 
    }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    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.tooltip' );
    }    

  };

})( jQuery );

// calls the init method
$('div').tooltip(); 

// calls the init method
$('div').tooltip({
  foo : 'bar'
});
4

0 回答 0