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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With