2012-02-25 103 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構造函數創建的對象,而不是從插件函數創建自己的對象。

有可能在你的插件代碼的內部某處使用構造函數,但它通常不會是實際的插件函數本身。