Reputation: 2081
I am using Twitter Typeahead in version 0.11.1. Now I am trying to get remote working correctly, but somehow I think I am getting strange behavior.
This is the working code with a local array:
var localArray = [{"value":"test0"},{"value":"test1"},{"value":"test2"},{"value":"test3"},{"value":"test4"}];
var myds = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: localArray
});
$(function () {
$("#my-input").typeahead({},
{
name: 'ds1',
source: myds,
display: 'value'
});
});
Now I try to setup remote data. What I did is just to change local to remote and provide the URL and add a query parameter. It will deliver exactly the same structure and data as localArray (it currently ignores the query and always delivers the content of localArray just to test this). I checked in Chrome Developer Tools that the query is actually executed and returns the content of localArray:
var myds = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/autocomplete?query=%QUERY',
wildcard: '%QUERY'
}
});
$(function () {
$("#my-input").typeahead({},
{
name: 'ds1',
source: myds,
display: 'value'
});
});
Somehow this does not work when searching for test
. When searching for tes
I still get results, but when I search for test
, no result is offered for autocompletion. There are other words for which this does not work, and it seems to follow the same schema, like a complete word is not found while parts of words are found. Any idea what causes this behavior or how to fix it?
My guess is that the remote datasource has to be in another format, but I cannot find how it has to look. All the examples on the typeahead page look very similar...
Upvotes: 3
Views: 387
Reputation: 11269
You are experiencing a bug in typeahead. It causes strange behavior when dealing with result sets that are the same as, or less than, the limit declared in typeahead (default limit is 5). Unfortunately the main typeahead repo is no longer maintained so you will either have to use a PR that fixes the issue or edit the code yourself. Luckily, the fix is just moving down one line of code.
Either in the compiled bundle or in src/typeahead/dataset.js
find this block of code and change it to:
function async(suggestions) {
suggestions = suggestions || [];
if (!canceled && rendered < that.limit) {
that.cancel = $.noop;
that._append(query, suggestions.slice(0, that.limit - rendered));
rendered += suggestions.length;
that.async && that.trigger("asyncReceived", query);
}
}
All this does is move rendered += suggestions.length;
below that._append(query, suggestions.slice(0, that.limit - rendered));
;
This is exemplified in this PR.
Upvotes: 3