Accessing widget instance from outside widget

Anders picture Anders · Dec 14, 2011 · Viewed 27.8k times · Source

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

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

this.hide();

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

Answer

Frédéric Hamidi picture Frédéric Hamidi · Dec 14, 2011

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

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

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