Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: {
    url: '/_dev_data_sources/last_adresses_json.html',
  },
  limit: 20
});



lastAdresses.initialize().done(function () {
  var query = "L";
  lastAdresses.get(query, function(suggestions) {
  console.log(suggestions);
  });
});

This works fine, when my query is "L" like in the example, or another string. But I want bloodhound to return all available Records, when my query is "". In my example, it returns nothing.

I saw, that bloodhound has a filter argument, but I don`t know how to use this.

Can somebody help me?

like image 434
user1383029 Avatar asked May 02 '14 13:05

user1383029


2 Answers

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:

  • Twitters Typeahed example with default suggestions
  • joews answer
like image 164
MJar Avatar answered Nov 20 '22 18:11

MJar


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

You can monkey patch SearchIndex.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 === '') {
      return this.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.

like image 43
joews Avatar answered Nov 20 '22 17:11

joews