我喜欢使用对象字面表示法来编写我的大部分功能,并且想知道与jQuery.fn插件表示法相比,其他人对此有何看法?
我发现以jquery“插件”的形式编写代码的问题是,你无法获得一个公共的“API”来使用。以这个简单的弹出框为例:
$.fn.popup = function() {
// insert #popupContainer
this.each(function() {
$(this).click(function() {
$('#popupContainer').show();
});
});
});
// DOM ready
$('a.showPopup').popup();如果不在DOM中查询#popupContainer并手动显示它,就没有其他接口来显示弹出窗口。
举个例子:
var popup = {
init: function() {
// insert #popupContainer
// bind this.show to $(a.showPopup)
}
show: function() { $('#popupContainer').show(); }
}这很好,因为它允许我随时调用popup.show(),而不必依赖于之前创建的绑定。
这个例子有点垃圾,但我希望你能看到我的想法,以及当功能更复杂时它的影响。
那么你更喜欢什么呢?
我很有兴趣听听你的想法?
发布于 2010-09-22 07:16:15
在第一个示例中第一次调用popup()时,不能简单地插入"#popupContainer“元素吗?这样一来,您根本就不需要调用init。
此外,在jQuery中,添加“全局”API函数的标准方法是直接将它们添加到$ object:
(function($) {
$.myPlugin = function() {
alert("1");
}
$.fn.myPlugin = function() {
alert(2);
}
})(jQuery);因此,现在您可以执行以下操作:
$.myPlugin(); // pops up "1"
$("whatever").myPlugin(); // pops up "2"发布于 2010-09-22 08:09:45
另一个未充分利用的选项是自定义事件,例如:
$.fn.popup = function() {
// insert #popupContainer
return this.each(function() {
$(this).bind({
"open.popup": function() { $('#popupContainer').show(); },
"click": function() { $(this).triggerHandler("open.popup"); }
});
});
});这可能不是一个很好的示例,但您可以这样做,例如:
$('a.showPopup').popup(); //initialize plugin
$('a.showPopup').trigger("open.popup"); //open the popup
$('a.showPopup').click(); //less explicit, but works...no need for the open bindhttps://stackoverflow.com/questions/3765130
复制相似问题