JQuery - 小部件公共方法
如果我创建一个 JQuery 小部件(下面的代码示例),然后定义一个“公共”方法,除了使用以下形式之外,还有其他方法来调用该方法吗?
$("#list").list("publicMethod");
我想创建一系列定义相同方法(基本上实现相同接口)的小部件,并且能够在不知道我当前正在调用哪个小部件的情况下调用该方法。在当前表单中,我需要知道我正在“列表”小部件上执行该方法。
下面是使用“public”方法创建小部件的示例。
(function($) {
var items = [];
var itemFocusIdx = 0;
$.widget("ui.list", {
// Standard stuff
options : { ... },
_create : function() { ... },
destroy : function() { ... },
// My Public Methods
publicMethod : function() { ... }
...
});
}(jQuery));
If I create a JQuery widget (code example below), and then define a "public" method, is there any other way to call the method other than using the following form?
$("#list").list("publicMethod");
I would like to create a series of widgets that all define the same methods (basically implementing the same interface), and be able to call the method without knowing anything about which widget I currently am invoking the method on. In the current form, I need to know that I am executing the method on the "list" widget.
Below is an example of creating a widget with the "public" method.
(function($) {
var items = [];
var itemFocusIdx = 0;
$.widget("ui.list", {
// Standard stuff
options : { ... },
_create : function() { ... },
destroy : function() { ... },
// My Public Methods
publicMethod : function() { ... }
...
});
}(jQuery));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
jQuery UI 小部件使用 jQuery 的 $.data(...) 方法间接将小部件类与 DOM 元素关联起来。在小部件上调用方法的首选方法正是 Max 所描述的...
...但是如果您想获取返回值,则通过 data 方法以这种方式调用它会更好:
但是,使用第二种方式回避了整个 jQuery UI 小部件模式,如果可能的话应该避免。
jQuery UI widgets use jQuery's $.data(...) method to indirectly associate the widget class with the DOM element. The preferred way to call a method on the widget is exactly what was described by Max...
...but if you want to field a return value, you'll have better luck calling it this way, via the data method:
However, using the second way side-steps the whole jQuery UI widget pattern, and should probably be avoided if possible.
我知道有点偏离主题,但您可能想看看 jquery Entwine。
这提供了一种继承和多态性的形式,允许使用简单的代码实现一些巧妙的行为。听起来这会做你想做的事情。
Slightly off-topic, I know, but you may want to look at jquery Entwine.
This provides a form of inheritance and polymorphism which allows some clever behaviour with simple code. It sounds like this would do what you are trying to do.
假设您有
list
、list2
和superList
...让我们为它们中的每一个调用“publicMethod”:lets say you have
list
,list2
, andsuperList
... let's call "publicMethod" on for each of them:这个解决方案的灵感来自于 @Jiaaro 的解决方案,但我需要一个返回值并作为 JavaScript 函数实现,而不是扩展 jQuery:
This solution is inspired by @Jiaaro's solution, but I needed a return value and implemented as a JavaScript function rather than extending jQuery:
试试这个:
Try this:
这个怎么样:
当您使用键:值对集扩展 ui.list 时
How about this one:
As you are extending ui.list with your key:value pair set