0

我正在玩弄一些创作插件,所以我转向了 jQuery 文档,其中讨论了不要弄乱 $.fn 对象,以及没有一个插件应该超过 $.fn 命名空间......

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

我明白了一切,直到:

      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));

部分。

我将那一点更改为:

$.fn.tooltip = function(method)
{
    if(myFunc[method])
    {
        return myFunc[method].apply();
    }
}

它工作得很好......有人可以向我解释那里发生了什么以及为什么我的工作似乎很好吗?

编辑:顺便说一句,我知道我没有完全继续 if/else 结构,那是因为我完全专注于我提到的行,而不是 if 结构的其余部分。

4

1 回答 1

1

您这样做的方式很好,但是,它不允许您将任何参数传递给您的方法。

例如,如果您的插件有一个option允许您更改工具提示文本选项的方法,您可以这样调用它:

$(element).tooltip("option","text","foobar!!");

如果您删除所有其他代码并使用您的方式执行此操作,则该option方法将不会接收"text"or"foobar!!!"参数。

于 2013-04-03T20:23:48.637 回答