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);
*「我對原型有點困惑。」*您對什麼感到困惑?只有你使用它的地方,你只是用它來獲取'.slice()'方法。如果你遵循「最佳實踐」,那麼你是否有理由認爲你的代碼會很糟糕? – 2012-02-25 16:23:53
哦,不,我只是在談論代碼的結構! 最近我發現了「原型」,所以我的問題是我仍然應該使用我的「方法調用邏輯$ .fn.tooltip ...」或者開始使用原型而不是? – macpie 2012-02-25 16:31:18
如果這可以幫助你http://heera.it/patterns-in-jquery-plugin-writin – 2012-02-25 16:34:20