Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
    }
});
like image 958
TheDude Avatar asked Apr 04 '16 13:04

TheDude


1 Answers

The "right" way to handle errors is adding an error handler to the AJAX call, using the prepare function. If you are using the wildcard option, notice that prepare overrides it.

For example, you can turn this:

new Bloodhound({
    remote: {
        url: REMOTE_URL,
        wildcard: '%s'
    }
});

into this:

new Bloodhound({
    remote: {
        url: REMOTE_URL,
        prepare: function(query, settings) {
            return $.extend(settings, {
                url: settings.url.replace('%s', encodeURIComponent(query)),
                error: function(jqxhr, textStatus, errorThrown) {
                    // show error message
                },
                success: function(data, textStatus, jqxhr) {
                    // hide error message
                }
            });
        }
    }
});

The object returned by prepare is used as a settings object for jQuery.ajax() so you can refer to its documentation.

like image 181
Tobia Avatar answered Oct 18 '22 07:10

Tobia