Show full list of suggestions on click with typeahead and bloodhound

大城市里の小女人 提交于 2019-12-01 06:36:13

问题


I am using Typeahead.js with the bloodhound suggestion engine and would like to make the list appear as soon as the user clicks in the search box.

I found this stackoverflow question (Twitter TypeAhead show all results programmatically) which is the same as me and the answer points to a jsfiddle solving the problem : http://jsfiddle.net/5xxYq/

Great.

However, it seems only to be working when not using bloodhound as the source for typeahead.

e.g. I forked their working example and switched the typeahead source to use bloodhound : http://jsfiddle.net/5xxYq/31/. The suggestion engine is working fine (when I type jo the list appears), but the little hack to make the suggestions appear on click does not seem to be working anymore.

Any idea on how to make the suggestions list appear on click with bloodhound?

Thanks!


回答1:


If you are using this solution in combination with bloudhound you will need to alter bloodhound.js or the bundle.js as well.

In typeahead.bundle.js or bloodhound.js add find this code (line 450)

return matches ? _.map(unique(matches), function(id) {
                return that.datums[id];
            }) : [];

Add this check to return all suggestions if the token input is empty:

if (tokens == '') return that.datums;

It will now look like:

if (tokens == '') return that.datums;
return matches ? _.map(unique(matches), function(id) {
                    return that.datums[id];
                }) : [];

I have tested this in your fiddle and it works.




回答2:


I think there might be a better way of doing this. Without altering the bloodhound/boundle js, but it still depends on internal bloodhound implementation that may change.

var searchEngine = new Bloodhound({...});
function searchWithDefaults(q, sync) {
  if (q === '') {
    sync(searchEngine.index.all());
  } else {
    searchEngine.search(q, sync);
  }
}
$("#typeahead").typeahead({
  minLength : 0,
}, {
  name : 'typeahead',
  source : searchWithDefaults
});

This code takes advantage of implementation of Bloodbound internal search engine called SearchIndex and its function all() that returns full list of data stored by Bloodhound.

Answer inspired by:

  • Twitters Typeahed example with default suggestions
  • stackoverflow answer for question 'typeahead.js: Return all Bloodhound records on empty query'


来源:https://stackoverflow.com/questions/27138123/show-full-list-of-suggestions-on-click-with-typeahead-and-bloodhound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!