2011-02-13 73 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

相關問題