2011-06-22 24 views
0

我創造,我的處理程序綁定到一個元素有點JQuery的UI插件:JQuery UI:將處理程序綁定到方法:無法獲取元素?

this.element.bind("keyup", { list: this.container }, this._filter); 

的部件有選擇:

options: 
{ 
    dataUrl: '', 
    isEnabled: true 
}, 
_filter: function (event) 
{ 
    var input = $(this); 
    var that = this; 
    alert(that.options.isEnabled); 
    if (that.options.enabled) { 
     that.container.show(); 
     event.data.list.find("li").each(function() { 
      if ($(this).text().toLowerCase().indexOf(input.val().toLowerCase()) < 0) { 
       $(this).hide(); 
      } 
      else { 
       $(this).show(); 
      } 
     }); 
    } 
}, 

但是當我做一個選擇的警報_filter,我得到一個錯誤:「that.options is undefined」 與我嘗試訪問/使用的任何其他元素相同,就像該函數只能獲取內部定義的內容或傳遞的eventData一樣。

我錯過了什麼嗎? 謝謝

回答

1

問題是,偵聽器函數(_filter)的範圍/上下文/這個jQuery對象也是綁定的。在你的情況下,在_filter函數中,當作爲事件監聽器被調用時,它實際上會引用該小部件的this.element。你可以做的是:

this.element.bind("keyup", { list: this.container }, $.proxy(this, "_filter")); 

代理方法做什麼,基本上是包裹,將在特定的情況下(see documentation)應用的功能。有關代理的好處是,你可以取消綁定使用原始的功能是這樣的:

this.element.unbind("keyup", this._filter); 

希望這有助於。

+0

謝謝! 另一個「work arround」是將元素作爲eventData屬性傳遞:'this.element.bind(「keyup」,{element:this.element,list:this.container},this._filter);' – user706058

相關問題