示例代碼:
var suggestion_source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("display_name"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "http://nominatim.openstreetmap.org/search?format=json&q=%QUERY",
wildcard: '%QUERY',
transform:function(response){
return response;
}
}
});
$('#addr').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
source: suggestion_source,
display:function(item){
return item.display_name;
},
templates: {
suggestion: function (data) {
return '<p style="text-align: left">' + data.display_name + '</p>';
}
}
});
默認的display就好,不需要去覆蓋
source是配置typehead的數據源
Bloodhound.tokenizers.obj.whitespace("city"),這個稍稍復雜一點,.whitespace("xxx")這個是指取"xxx"這個屬性,進行空白分詞,以便查詢.
比如返回的json,有一個屬性叫city,如果有一個具體的city="New York",那么進行了Bloodhound.tokenizers.obj.whitespace("city")之后,無論用戶輸入New或者York,都能查到,而不用考慮空格.
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("display_name"),
queryTokenizer: Bloodhound.tokenizers.whitespace,有兩個這個參數.
datumTokenizer是針對返回結果集的,
queryToken是針對查詢參數的.
template是定義每一行option的顯示效果的.
transform:對數據格式做轉化,如果有需要的話,比如把服務器的某個字段名改掉,或者某個字段進行數學計算