Twitter typeahaed.js - Change query source when certain characters are hit

80 views Asked by At

I'm using typeahead.js and would like to use a local array for the typeahead if the user has typed 3 or less characters, and then fall back onto a remote query if typing more than that. How can I implement an if statement in the source option of the typeahead? Below is my code now, but it's not working as intended. The source doesn't seem to like this method. When I call localTypeaheadData it doesn't get returned properly to the source.

var localTypeaheadData = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: localArray
});

$('#sitesearch').typeahead({
    minLength: 1,
},
{
    name: 'sitesearch',
    source: function (query, process) {
    if (query.length < 4) {
        return localTypeaheadData;
    } else {
        return remoteTypeaheadData;
    }
}
1

There are 1 answers

0
Tom Freezers On BEST ANSWER

It wasn't straight forward in the examples and the documentation left me hanging but I figured it out using the following code.

var localTypeaheadData = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: localArray
});

function searchData(query, sync, async) {
    if (query.length < 4) {
        localTypeaheadData.search(query, sync);
    } else {
        // something else
    }
}

$('#sitesearch').typeahead({
    highlight: true
},
{
    name: 'sitesearch',
    source: searchData
});