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();
You can also use the jQuery custom selector to find the widget elements before calling data on them to get the actual widget instance e.g.
That code finds all of the instances of ui.myDummyWidget (note the change of period . to hyphen - ) that have been created and attached to another widget holder.
The widget engine already does what you want: it calls data() internally to associate the widgets and their respective elements:
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:
Using unqualified names is still supported in 1.9 but is deprecated, and support will be dropped in 1.10.
I'm not sure in which version it was introduced but, if all you wish to do is calling a widget's method you can use this:
Where myWidget is the id of the DOM element holding an instance of your widget. This will call the hide method.
If the method you need to call needs parameters you can pass them after the method name, like this:
Also, you can look for all instances of your widget using the special selector :widgetName and call methods on them. The following code snippet will call the hide method on all myDummyWidget widgets.
Mind that the widget fullname is composed of a prefix ("ui" in the example) and the widget's name ("myDummyWidget") separated by a score ("-").
You should use your own prefix for your custom widgets; "ui" is generally reserved for jQueryUI pre-built widgets.
I hope that helps. :)
There is also a method created when a Widget is defined, you can simply call the
instance
method to get the actual Widget instance like so:Or you can do it as a one-liner: