typeahead, bloodhound : remote works but not prefetch

boblemar picture boblemar · May 9, 2014 · Viewed 12.5k times · Source

I want to use prefetch and I can't have it working ! Here is my code :

function initAutocompletion() {
    $("input[data-autocomplete-prefetch-url]").each(function () {
        var $this = $(this);
    var urlPrefetch = $this.data("autocomplete-prefetch-url");
    var prefetch;

    pref = {
        url: urlPrefetch,
        filter: filter
    };

    var bloodHound = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        prefetch: pref
    });

    bloodHound.initialize();

    $this
        .typeahead('destroy')
        .typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        },
        {
            displayKey: 'value',
            source: bloodHound.ttAdapter()
        });
    });
 }

function filter(list) {
    return $.map(list, function (v) { return { value: v.toString() }; });
}

It doesn't work.

If I use remote instead of prefetch it works !

    var bloodHound = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        remote: pref
    });

I can't anderstand.

Can anyone help me ?

Answer

boblemar picture boblemar · May 12, 2014

Amazingly it worked this morning ! So it drove me to think it was about cache... And it was ! Adding clearPrefetchCache() before initializing bloodhound did the trick.

       bloodHound.clearPrefetchCache();
       bloodHound.initialize();

I think it didn't show any suggestions because it has cached an empty list.