jQuery-ui:如何从私有函数内部访问选项 [英] jQuery-ui: How do I access options from inside private functions
问题描述
我正在学习使用widget-factory模式编写jquery-ui插件.对于更清洁的组织,我在传递给$.widget
的对象常量中定义了一些帮助程序方法.我想访问那些帮助器中的options对象.例如,在下面的样板中,如何访问_helper()
中的options对象?
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 );
谢谢.
推荐答案
因此,您正在_create
中进行此操作:
So you're doing this inside your _create
:
$(some_selector).click(this._helper)
,并且您希望_helper
中的this
成为this._helper
上的this
(即您的小部件).
and you want this
inside the _helper
to be the this
on this._helper
(i.e. your widget).
有多种解决方案:
-
您可以使用
$.proxy
$(some_selector).click($.bind(this._helper, this));
Underscore还具有 _.bind
,并且还有一个本地
Underscore also has _.bind
and there's a native Function.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.
您可以使用标准的var _this = this;
技巧代理_helper
自己呼叫:
You could use the standard var _this = this;
trick proxy the _helper
call yourself:
var _this = this;
$(some_selector).click(function() { _this._helper() });
您可以使用 eventData
形式的click
:
You could use the eventData
form of click
:
$(some_selector).click({ self: this }, this._helper);
,然后在_helper
中:
_helper: function(ev) {
var self = ev.data.self;
// 'self' is the 'this' you're looking for.
...
}
这篇关于jQuery-ui:如何从私有函数内部访问选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!