Search code examples
javascriptjquerytypeahead.jstypeaheadbloodhound

How is error handling done with the new Typeahead with Bloodhound?


I have an issue in which Typeahead simply stops working when the user federated session expires. I would like to be able to perform an action when the "remote" call for Typeahead fails. How is this handled with Typeahead in particular? Is there some sort of "error" callback like you would find in a typical ajax call? Here is the code that I currently have:

var hints = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace("value"),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "/ProjectAssociation/CountryLookup?query=%QUERY",
        wildcard: "%QUERY"
    }
});
$("#assocStoragesSelection").typeahead(null, {
    name: "nations",
    limit: 90,
    valueKey: "ShortCode",
    displayKey: "Name",
    source: hints,
    templates: {
        empty: [
            "<div class='noitems'>",
            "No Items Found",
            "</div>"
        ].join("\n")
    }
});

Solution

  • Typeahead's Bloodhound suggestion engine is lacking in facilities to inform the user when there is a problem with a remote source.

    Instead of using Bloodhound to get the suggestions you could instead use Typeahead's source source option (see here). By specifying your source here you can then handle errors and display a suitable message to the user.

    I've created an example here:

    http://jsfiddle.net/Fresh/oqL0g7jh/

    The key part of the answer is source option code shown below:

    $('.typeahead').typeahead(null, {
      name: 'movies',
      display: 'value',
      source: function(query, syncResults, asyncResults) {
        $.get(_url + query, function(movies) {
    
          var results = $.map(movies.results, function(movie) {
            return {
              value: movie.original_title
            }
          });
    
          asyncResults(results);
        }).fail(function() {
          $('#error').text('Error occurred during request!');
          setTimeout("$('#error').text('');", 4000);
        });
    }
    

    The source option is making use of jQuery's get method to retrieve the data. Any errors which occur are handled by the deferred object's fail method. In that method you can appropriately handle any errors and display a suitable message to the user. As the source function is specified with three parameters, this causes Typeahead to default this call as asynchronous, hence the call to:

    asyncResults(results);