Jamgreen
Jamgreen

Reputation: 11039

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.

Upvotes: 1

Views: 1191

Answers (1)

jloria
jloria

Reputation: 94

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

Upvotes: 0

Related Questions