0

我有一種感覺,這對大多數人來說是一個快速和容易的,但至少對我來說,解決方案是難以捉摸的。代理擴展jQuery小部件自動完成

我正在擴展jQuery自動填充小部件,以包含一些功能作爲默認。我需要在select事件中引用this.options.primaryField。

$.widget("mynamespace.myAutoComplete", $.ui.autocomplete, { 
    options: { 
     // our options 
     selectedId:0, 
     searchString:'', 
     indexField:'', 
     primaryField:'', 
     secondaryField:'', 

     // set existing ones 
     autoFocus: true, 
     minLength:3, 

     select: function(event,ui) { 
      // runs, but cant access this.options.<anything> 
     } 

    }, 

    _myselect: function (event,ui) { 
     //does not run 
     console.log("in myselect"); 
    }, 

    _renderItem: function (ul, item) { 
     var icon='marker'; 
     return $("<li>") 
      .append ('<div><a><i class=\"fi-' + icon + '"></i>' + item[this.options.primaryField] + "<br>" + item[this.options.secondaryField] + "</a><div>") 
      .appendTo (ul); 
    } 
}); 

我發現這裏的潛在解決方案: Howto access data held in widget options when inside a widget event handlerjQuery Widget Factory access options in a callback methodjQuery-ui: How do I access options from inside private functions

但我不能讓任何人的工作。這是我從這些解決方案產生的代碼。(當然它添加到$ .widget(...類)

_create: function() { 

     // does not fire _myselect on select 
     this._on(this.select, { change: "_myselect"}); 
     this._on(this.select, $.proxy(this._myselect, this)); 
     this._on(this.select, $.bind(this._myselect, this)); 

     this._super(); 
    }, 

我也試着將那些在_init功能以及我只是希望能夠設置this.options.selectedId,搜索字符串等被點擊的項目時

在此先感謝

回答

0

終於揭穿這對於任何人碰到同樣的問題:。

$.widget("ui.autocomplete", $.ui.autocomplete, { 
_init: function() { 
    this.element.on("autocompleteselect", $.proxy(this.myselect, this)); 
}, 
options: { 
    // our options 
    selectedId:0, 
    searchString:'', 
    indexField:'', 
    primaryField:'', 
    secondaryField:'', 
    .... 
}, 
myselect: function (event, ui) { 
    // event and ui work as normal 
    // this, refers to the widget, so the options are available via 
    // this.options.<blah> 
} 

我還應該指出,我在問題中選擇的名稱空間似乎也在問題中發揮了作用。如果我使用除ui.autocomplete以外的其他任何東西(我認爲這會使未修改的自動填充無法訪問 - 我曾經擁有此代碼)事件無法觸發。這就是說,即使命名空間爲ui.autocomplete,我在問題中提到的三個this._on ..命令仍然失敗