Typeahead.js: force reload of local dataset

I want to implement an initial fallback similar to the Twitter web application, where it has the final option to autocomplete the input value (for example, Search all people for {{input.val()}} ):

Fallback "Search all people for {{input.val ()}}

My current implementation failed because Typeahead.js does not reload local data arrays, so the desired effect only occurs in the first keyup event:

 var plusone = [ { value: '', tokens: '' } ]; $('#name').keyup(function () { plusone[0].value = $('#name').val(); plusone[0].tokens = $('#name').val(); }); $('#name').typeahead( [ { local: plusone } ] ); 

According to the documentation and this tutorial, it is not possible to reinitialize typeahead without destroying it first, which I would rather not have done for performance. Any suggestions for a better implementation or fix would be greatly appreciated (if anyone from Twitter is there, I would like to know your implementation).

+4
source share
1 answer

You can do this by adding a new dataset to typeahead using a custom source function.

 var nbaTeams = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: 'nba.json' }); nbaTeams.initialize(); $('#autosuggest-input').typeahead({ highlight: true, hint: false }, { name: 'nba-teams', displayKey: 'team', source: nbaTeams.ttAdapter(), templates: { header: '<h3 class="league-name">NBA Teams</h3>' } }, { name: 'advanced-search', displayKey: 'name', // For every dataset, typeahead expects you to provide a source property // which is a function that accepts two arguments: query and cb. And you // can do whatever you want in that function. In this case, what we do // is that regardless of the query provided, you will always return the // same result. source: function(query, cb) { var result = [{ 'name': 'Advance search for "' + query + '"' }]; cb(result); }, templates: { header: '<div style="border-top: 1px solid black;"></div>' } }); 

Demo and Credits: http://plnkr.co/edit/cjL6nZtShyxmLjWxzdBC?p=preview

+1
source

Source: https://habr.com/ru/post/1493072/


All Articles