我已经将Twitter Typeahead和Bloodhound组合成一个Knockout自定义绑定作为一个实验,到目前为止,我已经很好地工作了。但是我有一个用例,如果用户键入一个没有找到结果的搜索词,我想在列表中有一个可选条目。这不是默认情况下在typeahead中可用的东西,但我确实找到了this issue on Github,它演示了一个似乎符合要求的解决方法。麻烦的是我无法让它工作,我相当有限的Javascript智能已经用完了。
此解决方法的要点是,不是创建Bloodhound实例,然后将typeahead的source
属性设置为engine.ttAdaptor()
,而是执行以下操作:
var engine = new Bloodhound(/* ... */);
engine.initialize();
var emptyDatum = { val: 'i am suggestion shown when there are none!' };
var sourceWithEmptySelectable = function(q, cb) {
engine.get(q, injectEmptySelectable);
function injectEmptySelectable(suggestions) {
if (suggestions.length === 0) {
cb([emptyDatum]);
}
else {
cb(suggestions);
}
}
};
$('.typeahead').typeahead(null, {
// ...
source: sourceWithEmptySelectable
});
使用最新版本的typeahead(v0.11.1)我收到一个错误,只是说missing source
。查看Bloodhound的源代码,它看起来像engine.get(q, injectEmptySelectable)
调用不再有效,因为Bloodhound类上没有get
方法,其签名接受查询和回调。 Transport
课程中有一个,但我没有看到这个例子中使用的是怎样的。我在这方面是正确的,还是我错过了什么,还是有另一种方法来实现这个目标?