我想实现一个类似于Twitter的网络应用程序的原始后备选项,它具有输入值的最终自动完成选项(例如Search all people for {{input.val()}}
):
我当前的实现失败,因为Typeahead.js没有重新加载本地数据集,因此只在第一个keyup事件上发生了所需的效果:
var plusone = [
{
value: '',
tokens: ''
}
];
$('#name').keyup(function () {
plusone[0].value = $('#name').val();
plusone[0].tokens = $('#name').val();
});
$('#name').typeahead(
[
{
local: plusone
}
]
);
根据文档和tutorial,没有办法重新初始化typeahead而不首先破坏它,我不想为了性能而去做。任何有关更好的实施或修复的建议都会受到高度赞赏(如果有人来自Twitter,我很乐意了解您的实施情况)。
答案 0 :(得分:1)
您可以通过向自定义源函数预先输入新数据集来实现此目的。
var nbaTeams = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'nba.json'
});
nbaTeams.initialize();
$('#autosuggest-input').typeahead({
highlight: true,
hint: false
}, {
name: 'nba-teams',
displayKey: 'team',
source: nbaTeams.ttAdapter(),
templates: {
header: '<h3 class="league-name">NBA Teams</h3>'
}
}, {
name: 'advanced-search',
displayKey: 'name',
// For every dataset, typeahead expects you to provide a source property
// which is a function that accepts two arguments: query and cb. And you
// can do whatever you want in that function. In this case, what we do
// is that regardless of the query provided, you will always return the
// same result.
source: function(query, cb) {
var result = [{
'name': 'Advance search for "' + query + '"'
}];
cb(result);
},
templates: {
header: '<div style="border-top: 1px solid black;"></div>'
}
});
演示&amp;学分:http://plnkr.co/edit/cjL6nZtShyxmLjWxzdBC?p=preview