推荐jQuery插件的设计模式 - 传递选项或方法?

时间:2012-10-25 13:45:03

标签: jquery

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

然后在同一篇文章中,他们建议在一个名为methods的对象文字中收集所有插件的方法,并通过传递方法的字符串名称来调用给定的方法,如$.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'
});

0 个答案:

没有答案