Reputation: 2096
I have a jQuery UI widget which attaches to a div and then listens to specific controls inside it (set via options). The problem is that in my event listener, this refers to the control that changed, not the element the widget is attached to. So how can I access the widget element?
_addressChanged: function () {
$(this).data("address").requiresValidation = true;
},
_bindEventHandlers: function () {
$(this.options.address1).bind("change", this._addressChanged);
$(this.options.address2).bind("change", this._addressChanged);
$(this.options.city).bind("change", this._addressChanged);
$(this.options.zip).bind("change", this._addressChanged);
},
Upvotes: 0
Views: 136
Reputation: 5105
Use the this._on()
method to bind the handler. This method is provided by the jQuery UI widget factory and will make sure that within the handler function, this
always refers to the widget instance.
_bindEventHandlers: function () {
this._on(this.options.address1, {
change: "_addressChanged" // Note: pass the function name as a string!
});
...
},
_addressChanged: function (event) {
// 'this' is now the widget instance.
// 'this.element', as suggested by sjsharktank, is the DOM element the widget was created on
},
Upvotes: 1
Reputation: 861
Have you tried this.element
?
From http://wiki.jqueryui.com/w/page/12138135/Widget%20factory:
this.element
The element that was used to instantiate the plugin. For example, if you were to do
$( "#foo" ).myWidget()
, then inside your widget instancethis.element
would be a jQuery object containing the element with id foo. If you select multiple elements and call.myWidget()
on the collection, a separate plugin instance will be instantiated for each element. In other words,this.element
will always contain exactly one element.
Upvotes: 0