1

我試圖用數據庫中的數據實現autocompletegoog.ui.ac.AutoComplete以對象作爲數據源

的數據看起來像

[ 
    {"id":"1",name:"Jon"}, 
    {"id":"2",name:"Carl"}, 
    {"id":"3",name:"Jon"}, 
] 

沒有example使用這樣的數據,即使這會比從一堆字符串的選擇字符串比較常見。除非您知道ID,否則讓用戶選擇「Jon」並不意味着什麼。

我試圖添加代碼到下面的頁面,並聽取用戶選擇一個項目時的事件,但首先它沒有記錄在代碼和API中什麼事件是第二個事件似乎沒有被觸發。希望事件對象可以傳遞用戶選擇的對象(不是字符串)或所選項目的索引,因此我不必使用訪問私有變量來獲取所選對象。

ac1.dispose(); 
var DataItem = function(id,value){ 
    this.id=id; 
    this.value=value; 
}; 
DataItem.prototype.toString=function(){ 
    return this.value; 
}; 
DataItem.prototype.valueOf=function(){ 
    return this.value; 
}; 
var tcMovies = [ 
    new DataItem(1,"one"), 
    new DataItem(2,"onetwo") 
]; 
var ac1 = goog.ui.ac.createSimpleAutoComplete(
    tcMovies, document.getElementById('txtInput1'), false); 


goog.events.listen(ac1,goog.ui.ac.AutoComplete.EventType.SELECT, 
    function(e){ 
    //never gets called 
    console.log(e); 
    //hoping to get an index so I can do something like 
    // ac1.getMatcher().rows_[selectedindex].id 
    // probably should not use rows_ but there is no get 
    // method for that either 
    } 
); 

回答

1

擺弄一下,看看源代碼,我確實發現希望實現它的方法。在autocomplete.js下面的評論建議是正確的做法:

/** 
    * Field value was updated. A row field is included and is non-null when a 
    * row has been selected. The value of the row typically includes fields: 
    * contactData and formattedValue as well as a toString function (though none 
    * of these fields are guaranteed to exist). The row field may be used to 
    * return custom-type row data. 
    */ 
    UPDATE: 'update', 

打開following頁面,按F12並運行在控制檯下面的代碼。

//remove existing autocomplete 
ac1.dispose(); 
//define data, need toString 
// to display the values 
var DataItem = function(id,value){ 
    this.id=id; 
    this.value=value; 
}; 
DataItem.prototype.toString=function(){ 
    return this.value; 
}; 
// create data 
var tcMovies = [ 
    new DataItem(1,"abbbbbbbb"), 
    new DataItem(2,"aabbbbbbb"), 
    new DataItem(3,"aaabbbbbb"), 
    new DataItem(4,"aaaabbbbb"), 
    new DataItem(5,"aaaaabbbb"), 
    new DataItem(6,"aaaaaabbb"), 
]; 
// use easy method to create and attach the autocomplete 
var ac1 = goog.ui.ac.createSimpleAutoComplete(
    tcMovies, document.getElementById('txtInput1'), false); 

//listen to UPDATE 
goog.events.listen(ac1,goog.ui.ac.AutoComplete.EventType.UPDATE, 
    function(e){ 
    //e.row should be the selected value 
    console.log("user selected",e.row); 
    } 
);