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