简体   繁体   中英

Typeahead.js with remote data source

I have a json file which outputs

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

My typeahead.js script looks like

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. So instead of 'searching' through the elements "A", "B", "C" etc. it just gives me one suggestion "A, B, C, ...".

What is wrong with my script? I have followed the examples at 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". I am pretty sure it's the filter option inside prefetch which doesn't work correctly.

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. 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 }; });
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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