【发布时间】:2012-08-08 19:16:49
【问题描述】:
我正在学习使用小部件工厂模式编写 jquery-ui 插件。为了更简洁的组织,我在传递给$.widget 的对象文字中定义了一些辅助方法。我想访问这些助手中的选项对象。例如在下面的样板中,我如何访问 _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 );
谢谢。
【问题讨论】:
-
小部件工厂不认为带有前导下划线的方法是私有的吗?那你怎么打电话给
_helper? -
嗯,在 _create 方法中,this 指向对象字面量(第二个参数指向 $.widget),因此可以在 _create 中调用 this._helper()
-
但是你说 '"this" 指向 dom 元素' 那么
._helper()调用是什么样的呢?而_create是一个特殊的方法,它是小部件界面的一部分。 -
_helper 实际上是在 _create 中设置的“点击”事件的处理程序,如下所示:$(some_selector).click(this._helper)。因此,事件子系统在 DOM 元素上调用它。我正在寻找一种在 _helper 中使用 options 属性的方法。
标签: jquery-ui jquery-ui-plugins jquery-ui-widget-factory