2011-02-13 79 views
3

我正在为一个项目设计一个键盘小部件,我正在扩展$.ui.mouse。我需要点击行为(不由_mouseCapture触发)。我很难在里面找回this.options。请参见下面的代码块:如何在jQuery小部件中获取小部件实例?

$.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(这非常逻辑)。

还有其他方法吗?哪一个最适合挑选?

感谢,

回答

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-获得自我

+0

内``_mouseClick`这`是我刚才点击的dom元素。所以this.options不会被设置。 – Olivier 2011-02-13 20:07:19

相关问题