Using Typeahead.js without Bloodhound

comments 14
programming

A great library for adding typeahead support to your site is Twitter’s Typeahead.js. Even better is the excellent Bloodhound suggestion engine which comes with it. Sometimes though if you’re dealing with a remote suggestion engine like Elasticsearch’s completion suggester you don’t need to run remote results once again through another suggestion engine. Bypassing Bloodhound is as simple as hooking your own source function into your Typeahead definition.

 

14 Comments

  1. wdiechmann says

    btw – did you manage to circumvent the ‘fails to show results on 2 or more chars in querystring’ ?
    eg:
    data = { ‘m-1-1’, ‘m-2-1’, ‘m-2-2’ }
    result.length on q= ‘m’ => 3
    result.length on q= ‘m-2’ => 0

    result.length is 2 from server (remote) but none are displayed :/

    • Sorry, I’m not entirely sure what you mean. So you’re returning 2 results from the server but none are being displayed? You need to make sure the JSON you return is formatted correctly for typeahead.js. I believe it wants the values like [{“value”: “m-1-1”},{“value”: “m-2-1”}] if that’s what you are returning.

      • wdiechmann says

        oh – nice of you to get back to me on this one!
        but I ‘meddled’ with the src – and made a PR on a small change to async (with limits set to 5 and having 5 answers back from the server, the current version of Typeahead.js does nothing good for shows :)

        cheers

  2. Aaron Bauman says

    So simple, but exactly the solution for my problem! I just started using Elasticsearch and I thought typeahead was just a little bit slower than what it should be!
    Thank you so much for this post!

  3. Данил Прокопчук says

    Good solution, if you want to send request after each character has been typed…

    • Scott says

      I ended up using underscore with its built-in debounce function to handle this. Just add

      https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js
      

      Example below.

      
          var fetchQuery = null;
          var fetchResultsCallback = null;
      
          var fetchResults = _.debounce(function(){
              $.get('/search' + fetchQuery, function(data) {
                  if(fetchResultsCallback)
                      fetchResultsCallback(data);
                });
          }, 300);
      
          $('.typeahead').typeahead({
              minLength: 3,
              highlight: true,
            },
            {
              name: 'stuff',
              display: 'value',
              source: function(query, syncResults, asyncResults) {
                  fetchQuery = query;
                  fetchResultsCallback = asyncResults;
                  fetchResults();
              }
            });
      
      

Leave a Reply to Scott Cancel reply

Your email address will not be published.