我正在为一个项目开发一个键盘小部件,我正在扩展$.ui.mouse
。我需要点击行为(不是由_mouseCapture触发)。我很难回到this.options
里面。请参阅下面的代码块:
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create : function() {
this.element.bind('click.'+this.widgetName, this._mouseClick);
},
_mouseClick: function(e) {
// how do i get this.options here
}
});
最好这样做:
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create : function() {
var self = this;
this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
},
_mouseClick: function(e, self) {
// how do i get this.options here -> self.options
}
});
或者这个:
$.widget("ui.keyboard", $.ui.mouse, {
widgetEventPrefix: "keyboard",
options: {
[...]
},
[...],
_create : function() {
this.element.bind('click.'+this.widgetName, this._mouseClick);
},
_mouseClick: function(e) {
var self = $.data(this, "keyboard");
// how do i get this.options here -> self.options
}
});
当我尝试手动触发时,我遇到了最后一个问题$ .data没有启动,除非我触发点击this.element
(这是非常逻辑的)。
还有其他方法吗?哪一个最好选择?
谢谢,
答案 0 :(得分:1)
你可以调用一个匿名函数来返回一个对象,如下所示:
$.widget("ui.keyboard", $.ui.mouse, function(){
var self;
return {
widgetEventPrefix: "keyboard",
options: {
[...]
},
_create : function() {
self = this;
this.element.bind('click.'+this.widgetName, function(e) { self._mouseClick(e, self); });
},
_mouseClick: function(e, self) {
// do something with self.options
}
}
}());
这样您就可以在_mouseClick -
中访问self