我正在學習使用widget-factory模式編寫jquery-ui插件。爲了組織更清潔,我在對象字面量中定義了一些幫助器方法,這些方法被傳遞給$.widget
。我想訪問這些助手中的選項對象。例如在下面的樣板中,如何訪問_helper()
內的選項對象?jQuery-ui:我如何從私有函數中訪問選項
;(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);
謝謝。
具有前導下劃線的方法是否被widget工廠認爲是私有的?那你怎麼叫'_helper'? – 2012-08-12 03:39:45
那麼,在_create方法中,這指向對象字面量(第二個參數爲$ .widget),因此可以在_create內部調用this._helper() – 2012-08-12 03:49:26
但是,你說''this'指向dom元素'那麼'._helper()'調用的樣子是什麼? '_create'是一個特殊的方法,它是widget界面的一部分。 – 2012-08-12 03:54:59