Skip to content Skip to sidebar Skip to footer

Typeahead.js: Return All Bloodhound Records On Empty Query

i use bloodhound to get some data for typeahead. My Bloodhound Object: var lastAdresses = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryT

Solution 1:

I think there might be a better way of doing this. 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:

Solution 2:

Bloodhound uses an internal type called SearchIndex for efficient matching of query terms.

You can monkey patchSearchIndex.get to change the records that are returned for a given query.

This function patches a Bloodhound instance to return all records for an empty query term:

// Patch the given Bloodhound instance//  to match all records for an empty query
function enableMatchAll(bloodhound) {
  var _get = bloodhound.index.get;
  bloodhound.index.get = function(query) {
    if(!query || query === '') {
      returnthis.datums;
    } else {
      return _get.call(this, query);
    }
  }
}

JSBin demo

Be aware that this patch uses undocumented internal functionality. It works for typeahead/bloodhound v0.10.5; it may or may not work with any other version.

Post a Comment for "Typeahead.js: Return All Bloodhound Records On Empty Query"