Typeahead js with Bloodhound- this.source is not a function

DLeh picture DLeh · May 21, 2015 · Viewed 10.3k times · Source

I'm following this example for typeahead.js using Bloodhound to the T, but I'm getting a javascript error. What am I missing?

HTML: (.net razor view)

@Scripts.Render(Links.Scripts.typeahead_bundle_js) 
@Styles.Render(Links.Content.typeahead_min_css)
<input id="myInput" type="text" class="form-control" />

JS:

$(function () {
    var data = ["abce", "abcd", 'def', 'abcdef'];
    var bh = new Bloodhound({
        local: data,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        datumTokenizer: Bloodhound.tokenizers.whitespace
    });
    //bh.initialize(); //this wasn't in the example, adding it had no effect

    $('#myInput').typeahead({
        highlight:true
    },
    {
        name: "testData",
        source: bh
    });
});

gives the error in typeahead.bundle.js:

this.source is not a function

Answer

bosskovic picture bosskovic · May 28, 2015

This one gave me a hard time too, because, same as you, I was doing everything to the letter as in the example... I took me a while to check the exact version of the lib that I use and compare it to the one in the example. I was using the typeahead.js 0.10.5 packaged in the 'twitter-typeahead-rails' gem, and in the examples the version used is typeahead.js 0.11.1.

As soon as I switched the version, everything started working as it should. There was even no need to re-map the array of strings into array of objects or to call ttAdapter on the source. Your code will probably work the way you posted it too...


Quote from twitter-typeahead changelog for the version 0.11..0:

...There are bunch of API changes with this release so don't expect backwards compatibility with previous versions. There are also many new undocumented features that have been introduced. Documentation for those features will be added before v1 ships. ...