jqueryjquery-uiwidgetjquery-ui-widget-factory

jQuery UI Widget Factory get context of current widget


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.


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