2012-02-25 106 views
3

我想写一个“好”的jQuery插件结构。我试图遵循jQuery.com和其他人的“最佳实践”。最好的jQuery插件Strucure?

但我对原型有点困惑。

我应该使用它吗?实际结构看起来好还是可怕?

谢谢!

(function($){ 
    var defaults = { /* ... */ }, 
    publicMethods = { 
     add: function(options){ 
      var $this = $(this); 
      // ... 
      return $this; 
     } 
    }, 
    privateMethods = { 
     init: function(options) { 
      var $this = $(this); 
      return $this; 
     }, 
     click: function() { 
      //... 
     } 
    }; 
    $.fn.tooltip = function(method) { 
     var args = arguments; 

     $(this).each(function() { 
      if (publicMethods[method]) { 
       return publicMethods[ method ].apply(this, Array.prototype.slice.call(args, 1)); 
      } else if (typeof method === 'object' || ! method) { 
       return privateMethods.init.apply(this, args); 
      } else { 
       $.error('Method ' + method + ' does not exist on jQuery.tooltip'); 
      } 
     }); 
    }; 
})(jQuery); 
+0

*“我对原型有点困惑。”*您对什么感到困惑?只有你使用它的地方,你只是用它来获取'.slice()'方法。如果你遵循“最佳实践”,那么你是否有理由认为你的代码会很糟糕? – 2012-02-25 16:23:53

+0

哦,不,我只是在谈论代码的结构! 最近我发现了“原型”,所以我的问题是我仍然应该使用我的“方法调用逻辑$ .fn.tooltip ...”或者开始使用原型而不是? – macpie 2012-02-25 16:31:18

+0

如果这可以帮助你http://heera.it/patterns-in-jquery-plugin-writin – 2012-02-25 16:34:20

回答

1

对于使用tooltip功能的.prototype,这将是只有在提示功能将被援引作为一个构造函数是有用的。

通常作为一个jQuery插件,您只想使用从jQuery构造函数创建的对象,而不是从插件函数创建自己的对象。

有可能在你的插件代码的内部某处使用构造函数,但它通常不会是实际的插件函数本身。