Show full list of suggestions on click with typeahead and bloodhound

我怕爱的太早我们不能终老 提交于 2019-12-01 08:48:12

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.

MJar

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:

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