简体   繁体   English

带有远程数据源的Typeahead.js

[英]Typeahead.js with remote data source

I have a json file which outputs 我有一个输出的json文件

{"data": ["A", "B", "C", "D", ...]}

My typeahead.js script looks like 我的typeahead.js脚本看起来像

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list, function(person) { return { name: person }; });
        }
    }
});

engine.initialize();

$('.typeahead').typeahead(null, {
    displayKey: 'name',
    source: engine.ttAdapter()
});

The typeahead.js script is activated correctly, but it interprets the data source as only one comma separated item instead of separate items. typeahead.js脚本已正确激活,但是它将数据源解释为仅一个逗号分隔的项目,而不是单独的项目。 So instead of 'searching' through the elements "A", "B", "C" etc. it just gives me one suggestion "A, B, C, ...". 因此,与其“搜索”元素“ A”,“ B”,“ C”等,不如给我一个建议“ A,B,C,...”。

What is wrong with my script? 我的脚本有什么问题? I have followed the examples at http://twitter.github.io/typeahead.js/examples/ . 我已经在http://twitter.github.io/typeahead.js/examples/中遵循了这些示例。

If I change "name" to "value" both in datumTokenizer, filter and displayKey it wont get any items at all, but only output "undefined". 如果我在datumTokenizer,filter和displayKey中都将“ name”更改为“ value”,则根本不会得到任何项目,而只会输出“ undefined”。 I am pretty sure it's the filter option inside prefetch which doesn't work correctly. 我很确定这是预取中的filter选项无法正常工作。

In the filter function you are iterating over the properties of the object: 在过滤器功能中,您正在遍历对象的属性:

{"data": ["A", "B", "C", "D", ...]}

in this case, you are iterating over "data" only. 在这种情况下,您仅在“数据”上进行迭代。 For iterate over the items in "data", you should pass list.data to the filter function. 要遍历“数据”中的项目,应将list.data传递给过滤器函数。 In this way: 通过这种方式:

var engine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
        url: 'list.json',
        filter: function(list) {
            return $.map(list.data, function(person) { return { name: person }; });
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM