How do I list objects for Typeahead.js and/or with the Bloodhound engine?

孤街醉人 提交于 2019-12-04 14:17:07

The JSON file contains an array of JSON objects, but the Bloodhound suggestion engine expects an array of JavaScript objects.

Hence you need to add a filter to your prefetch declaration:

prefetch: {
 url: '../data/test.json',
 filter: function(names) {
   return $.map(names, function(name) { 
    return { name: name };
 });
}

As for the "datumTokenizer", it's purpose is to determine how the datums (i.e. the suggestion values) should be tokenized. It is these tokens which are then used to find a match with the input query.

For instance:

Bloodhound.tokenizers.whitespace("name")

This takes a datum (in your case a name value) and splits it into two tokens e.g. "Bob Marley" will be split into two tokens, "Bob" and "Marley".

You can see how the whitespace tokenizer works by viewing the typeahead source:

function whitespace(str) {
 str = _.toStr(str);
 return str ? str.split(/\s+/) : [];
}

Note how it splits the datums using the regex for whitespace (\s+ i.e. one or more occurrences of whitespace).

Similarly, the "queryTokenizer" also determines how to tokenize the search term. Again, in your example you are using the whitespace tokenizer, so a search term of "Bob Marley" will result in the datums "Bob" and "Marley".

Hence with the tokens determined, if you were to search for "Marley", a match would be found for "Bob Marley".

I have a simpler option, what you have done is correct except one small error. Actually you can use an object array as you have shown.

Replace displayKey: 'name' with display: 'name' and it should work.

So, the full typeahead function will look like

$('#test .typeahead').typeahead({
    name: 'names',
    display: 'name',
    source: names.ttAdapter()
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!