Question

Is there a global reference to the widget itself once it's been created using the jQuery UI widget factory pattern?

I've tried doing things like setting a widget var equal to the widget:

$.widget("my.widget", {
  _widget: this,
  _create: function () {
    // _widget should == the whole widget
  }
});

I've also tried grabbing the context of the widget through jQuery like:

$.widget("my.widget")

I can't figure out how you're supposed to be able to call back to the widget, while inside of the widget.

Was it helpful?

Solution

Whilst inside a widget method you refer to the instance via the 'this' keyword:

$.widget('my.widget', {
    foo: true,
    _create: function () {
        var foo = this.getFoo();
    },
    getFoo: function () {
        return this.foo;
    }

});

If you're in a method and find that the context has changed (as is often the case when writing jQuery) then you can just store a reference to 'this' in a local var:

$.widget('my.widget', {
    foo: true,
    _create: function () {
        var self = this;
        this.element.click(function () {
            var foo = self.getFoo();
        });
    },
    getFoo: function () {
        return this.foo;
    }

});

OTHER TIPS

As was mentioned earlier, this is the most common way to call widget functions from the widget.

In your example, it doesn't make sense to do this:

_widget: this

because you would need the context already to get to the _widget variable.

Sometimes its not possible to save the context in an easily accessible place, like when creating an event handler on an event that is not coming directly from the widget.

From Learning To Use the Widget Factory

If you can get the control, either from an event.target instance, or from the id of the control, you can call the .data() function on the jQuery object, passing the name of the widget. However, use a dash, instead of a dot, in the name of the widget.

var $control = $('#' + myControlId);
var $widget = $control.data("my-widget");
$widget.getFoo();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top