用jQuery封装UI组件
问题描述:
我正在构建一个涉及创建几个独特的UI“窗口小部件”的应用程序,并且我很难找出用jQuery封装这些UI组件背后的逻辑的良好实践。这些主要是一次性组件,不会在应用程序中的多个地方重复使用。用jQuery封装UI组件
我一直在试验lowpro plugin,虽然它确实允许我想要的更多或更少,但我觉得我会通过使用它来反对“jQuery方式”。
为了提供一些上下文,下面是使用lowpro编写的内容的简短摘录。这是一个可排序的列表,其他元素可以用药。当它初始化为空时,它显示一个占位符。
FieldList = $.klass({
initialize: function() {
this.placeholder = $('#get-started-placeholder');
if (this.items().length == 0) {
this.deactivateList();
} else {
this.activateList();
}
},
items: function() {
return this.element.children('li:visible');
},
deactivateList: function() {
this.element.hide();
this.element.sortable('destroy');
this.placeholder.show();
var instance = this;
this.placeholder.droppable({
hoverClass: 'hovered',
drop: function(e, ui) { instance.receiveFirstField(ui.helper); }
});
},
activateList: function() {
this.placeholder.hide();
this.placeholder.droppable('destroy');
this.element.show();
var instance = this;
this.element.sortable({
placeholder: 'placeholder',
forcePlaceholderSize: false,
tolerance: 'pointer',
handle: 'h4',
opacity: 0.9,
zIndex: 90,
stop: function(e, ui) { instance.receiveField(ui.item); }
});
},
receiveFirstField: function(element) {
...
this.activateList();
},
receiveField: function(element) {
...
}
});
$(function() {
$('ol#fields').attach(FieldList);
}
请注意,我有一点的状态会在这里,而且我希望我能做出一些实例方法私人等,所以,任何jQuery的利弊,有可以告诉我,他们怎么可以这样做而不依赖像lowpro这样的东西,这可能会使Javsacript变成它不应该是的东西?我有一种感觉,有一种干净的方式来完成这样的模块模式,我看到提到in this thread,但这些作品并没有真正为我而来。
谢谢!
答
使用jQuery UI "widget factory"。这是所有其他UI小部件(手风琴,对话等)使用的。
有一个确定的,但有点混淆的教程here。 (这是最好的一个,我发现。)
基本上,你在一个更jQuery的方式定义窗口小部件,如:
$.widget("ui.myCustomWidget", {
_init: function(){
//initialize your function
},
somethingElse: function(){
//do something else here
}
});
下划线函数名前会使其私有。您还可以设置窗口小部件功能集成到一个对象,并访问变量,如果这就是你想要的东西:
var foo = {
_init: function(){
//yada yada
},
somethingElse: function(){
//do something else here
}
};
$.widget("ui.myCustomWidget", foo);
然后你只需“创造”你的widget创建的任何其他UI插件的一样:
$('div#myWidget').myCustomWidget();
多种选项和内置的jQuery工具,允许您构建自己的小部件。不过,我不会让它成为教程,而是让你自己阅读所有关于它们的内容。快乐的插件!