从外部小部件访问小部件实例 [英] Accessing widget instance from outside widget

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

问题描述

这是一个简单的小部件模拟:

This is a simple widget mock:

(function ($) {

    $.widget("ui.myDummyWidget", {

        options: {
        },

        _create: function () {
        },
        hide: function () {
            this.element.hide();
        },
        _setOption: function (key, value) {
            $.Widget.prototype._setOption.apply(this, arguments);
        },

        destroy: function () {
            $.Widget.prototype.destroy.call(this);
        }

    });

} (jQuery));

它仅添加了一个方法hide,您可以调用该方法来隐藏元素.如果在窗口小部件中完成

It only adds a method hide that you can call to hide the element. Easy if done from within widget

this.hide();

但是常见的情况是您想从外部调用小部件实例上的方法(Ajax更新或其他外部事件)

But a common scenario is that you want to call methods on a widget instance from the outside (Ajax update, or other external events)

那么访问小部件实例的最佳方法是什么?一种方法是将对小部件的引用添加到元素中,很丑...

So what is the best way of accessing the widget instance? One way is to add the reference to the widget to the element, ugly...

_create: function () {
    this.element[0].widget = this;
},

然后您可以从外部访问它

Then you can access it from the outside doing

this.dummy = $("#dummy").myDummyWidget();
this.dummy[0].widget.hide();

推荐答案

小部件引擎已经完成了您想要的操作:它调用

The widget engine already does what you want: it calls data() internally to associate the widgets and their respective elements:

$("#dummy").myDummyWidget();
// Get associated widget.
var widget = $("#dummy").data("myDummyWidget");
// The following is equivalent to $("#dummy").myDummyWidget("hide")
widget.hide();

更新: :从jQuery UI 1.9开始,

Update: From jQuery UI 1.9 onwards, the key becomes the widget's fully qualified name, with dashes instead of dots. Therefore, the code above becomes:

// Get associated widget.
var widget = $("#dummy").data("ui-myDummyWidget");

在1.9中仍支持使用非限定名称,但已弃用,并且在1.10中将不再支持.

Using unqualified names is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.

这篇关于从外部小部件访问小部件实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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