【问题标题】:Polymorphism with jQuery UI WidgetsjQuery UI 小部件的多态性
【发布时间】:2015-01-30 06:07:02
【问题描述】:
我正在考虑将继承与 jQuery UI 小部件一起使用,以帮助简化我正在处理的一些代码。但是,我需要能够对基本小部件类型进行操作,即使它是被初始化的继承类型。
例如,假设一个小部件bar 继承自一个小部件foo,我像这样初始化了一个对象:
$('.something').bar();
有时我需要能够做到这一点:
$('.something').foo('someMethod');
到目前为止,我还无法让这样的事情发挥作用。
有没有办法做到这一点?
【问题讨论】:
标签:
javascript
jquery
user-interface
inheritance
widget
【解决方案1】:
【讨论】:
-
请注意 link-only answers 是不鼓励的,所以答案应该是寻找解决方案的终点(而不是另一个参考中途停留,随着时间的推移往往会变得陈旧)。请考虑在此处添加独立的概要,并保留链接作为参考。
【解决方案2】:
为了亲自解决这个问题,我编写了一个插件,它允许您在不知道小部件是什么type 的情况下调用小部件方法。这将允许您这样做:
$('.something').callWidgetMethod('someMethod', 'arg1', 'arg2');
它允许您执行诸如“禁用”页面上的所有小部件之类的操作(例如):
$('*').callWidgetMethod('disable');
它依赖于您使用 jQuery UI 1.11+。如果你使用的是"Skip this widget if it does not have the method"检查,但缺点是如果你尝试调用会报错小部件没有的方法。
插件代码:
jQuery.fn.callWidgetMethod = function () {
var args = arguments;
var result = null;
if(!this || !this.length)
return this;
this.each(function (i,o) {
var compClass = $(this).data("widgetName");
var func = $(this)[compClass];
// Skip this element if it does not appear to be an initialised jQuery widget
if(!compClass || !func)
return true;
// Skip this widget if it does not have the method (the name of which will be in args[0])
// This relies on the 'instance' method provided in jQuery UI 1.11
if(args.length>1 && !$(this)[compClass]("instance")[args[0]])
return true;
result = func.apply($(this),args);
});
if(this.length>1)
return this;
else
return result;
};