I am learning to write jquery-ui plugins using the widget-factory pattern. For cleaner organization, I have some helper methods defined inside the object literal that is passed to $.widget. I would like to access the options object in those helpers. For example in the boilerplate below, how do I access the options object inside _helper()?
;(function ( $, window, document, undefined ) {
$.widget( "namespace.widgetName" , {
options: {
someValue: null
},
_create: function () {
// initialize something....
},
destroy: function () {
$.Widget.prototype.destroy.call(this);
},
_helper: function () {
// I want to access options here.
// "this" points to the dom element,
// not this object literal, therefore this.options wont work
console.log('methodB called');
},
_setOption: function ( key, value ) {
switch (key) {
case "someValue":
//this.options.someValue = doSomethingWith( value );
break;
default:
//this.options[ key ] = value;
break;
}
$.Widget.prototype._setOption.apply( this, arguments );
}
});
})( jQuery, window, document );
Thank you.
So you're doing this inside your
_create:and you want
thisinside the_helperto be thethisonthis._helper(i.e. your widget).There are various solutions:
You could use
$.proxyUnderscore also has
_.bindand there's a nativeFunction.bindif you don't have to worry about JavaScript version issues). Other libraries will have their own function binding tools. You already have jQuery in play so$.proxyis already available and portable as well.You could use the standard
var _this = this;trick proxy the_helpercall yourself:You could use the
eventDataform ofclick:and then in
_helper: