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); 
    } 
);