3

“官方”文档http://docs.jquery.com/Plugins/Authoring#Namespacing声明方法应该添加到 jQuery 插件中,如下所示。我还没有看到这种设计模式经常实现。看起来如果其他插件使用 var 方法,可能会有冲突。这真的是首选方法,还是我应该采取不同的做法?

(function( $ ){

 var methods = {
  method1: function( options ) {},
  method2: function( ) {}
 };

 $.fn.tooltip = 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 );
  }
 };

})( jQuery );
4

1 回答 1

0

如果您想让这些方法公开访问,那么可以,这是首选方法。如果插件非常复杂,另一个可能且有时建议的选项是实际创建一个完整的构造对象,而不仅仅是使用方法哈希。我不知道这真的需要再做,因为您可以.data()在每个实例的根元素上管理状态使用,但它是我以前见过并且也欣赏过的模式。

<rant>此外,我最近对很多插件感到不满……如果你打算开源,请确保你至少包含一个destroy方法来解除你所做的一切。</rant>

于 2012-10-24T13:02:31.703 回答