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
this
inside the_helper
to be thethis
onthis._helper
(i.e. your widget).There are various solutions:
You could use
$.proxy
Underscore also has
_.bind
and there's a nativeFunction.bind
if 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$.proxy
is already available and portable as well.You could use the standard
var _this = this;
trick proxy the_helper
call yourself:You could use the
eventData
form ofclick
:and then in
_helper
: