jQuery-小部件公共方法 [英] JQuery - Widget Public Methods

查看:87
本文介绍了jQuery-小部件公共方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个JQuery小部件(下面的代码示例),然后定义一个"public"方法,除了使用以下形式之外,还有其他方法可以调用该方法吗?

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.

下面是使用"public"方法创建窗口小部件的示例.

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));

推荐答案

jQuery UI小部件使用jQuery的$ .data(...)方法将小部件类与DOM元素间接关联.在小部件上调用方法的首选方式正是Max ...描述的方式.

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...

$('#list').list('publicMethod');

...但是如果您想返回一个返回值,那么最好通过数据方法以这种方式调用它:

...but if you want to field a return value, you'll have better luck calling it this way, via the data method:

$('#list').data('list').publicMethod();

但是,使用第二种方法避开了整个jQuery UI小部件模式,如果可能的话,应该避免使用它.

However, using the second way side-steps the whole jQuery UI widget pattern, and should probably be avoided if possible.

这篇关于jQuery-小部件公共方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆