rpm*_*rtz 9 javascript typeahead.js twitter-typeahead
我正在使用typeahead.js 0.9.3并且它正在游泳.我的问题是,是否可以在"typeahead:selected"事件(或任何事件)上从数据集中删除数据.
我prefetch在页面加载时使用Typeahead 选项获取数据集中的数据.我知道我可以调用$('selector').typeahead('destroy')并重新使用typehead并filter在prefetch对象中使用a ,但是重新调用数据似乎相当重要(我们不会在本地存储中缓存数据).
我想我正在寻找类似于filter函数的东西来遍历基准数组并删除先前选择的(或所有选定的)基准.看起来没有类型的公共功能可以做到这一点,但也许我错过了它.
我通过typeahead的文档阅读并在此搜索但未找到答案.
编辑:我解决了直接的问题,通过切换prefetch到local和使用AJAX post调用来获取数据,将其设置为全局变量然后传递给typeahead我,在那里我可以从全局数据数组中添加/删除项目,然后销毁/根据需要重新开始先行.远非理想,但它的工作原理.
lik*_*phy 14
您可以在任何Bloodhound数据集上的Typeahead 0.10中实现此功能,无论是远程,预取还是本地.
只需跟踪独立于Bloodhound数据集选择的数据,不要Bloodhound#ttAdapater()用作您的预先输入源.ttAdapter方法只是一个包装器Bloodhound#get(query, cb)- 所以代替它,get(query, cb)直接使用自定义回调调用,该回调根据当前选择检查每个建议.
这是一个JSFiddle - http://jsfiddle.net/likeuntomurphy/tvp9Q/
var selected = [];
var select = function(e, datum, dataset) {
selected.push(datum.val);
$("#selected").text(JSON.stringify(selected));
$("input.typeahead").typeahead("val", "");
}
var filter = function(suggestions) {
return $.grep(suggestions, function(suggestion) {
return $.inArray(suggestion.val, selected) === -1;
});
}
var data = new Bloodhound({
name: 'animals',
local: [{ val: 'dog' }, { val: 'pig' }, { val: 'moose' }],
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.val);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
// custom suggestion filter is applied after Bloodhound
// limits the set of possible suggestions
// see comment by Basti below
limit: Infinity
});
data.initialize();
$('input.typeahead').typeahead(null,
{
name: 'animals',
displayKey: 'val',
/* don't use
source: data.ttAdapter(), */
source: function(query, cb) {
data.get(query, function(suggestions) {
cb(filter(suggestions));
});
},
templates: {
empty: '<div class="empty-message">No matches.</div>'
}
}
).bind('typeahead:selected', select);
Run Code Online (Sandbox Code Playgroud)
正如您所指出的,如果不对当前的预输入版本进行大规模黑客攻击,这即使不是不可能,也是很棘手的。您需要 3 样东西:
下一个 typeahead 版本(0.10 目前正在开发中)可能支持所需的功能。
但是...碰巧我的 (Svakinn) typeahead fork 支持您需要的所有三个条件。您的配置应该提供 getter 函数,您可以在其中从初始化数据中选择数据,并通过查询字符串和已选择的选项对其进行过滤。
remote: yourGetterFunction
Run Code Online (Sandbox Code Playgroud)
然后您需要禁用建议缓存:
skipCache: true
Run Code Online (Sandbox Code Playgroud)
如果您不想等待下一个 typeahead 版本,我建议您尝试一下:https:
//github.com/Svakinn/typeahead.js/tree/typeaheadSimple
还有可用的实时 JQuery 和 Knockout 示例:
https: //github.com/Svakinn/typeahead.js/blob/typeaheadSimple/Examples.md