Jason Kim's Blog

High level steps to setting up Twitter Typeahead.js to work with Backbone.js


To use Twitter Typeahead.js with Backbone.js, you need to set up the typeahead function in a Backbone view's render(). And you need to style the typeahead dropdown appropriately with css.

What is Twitter Typeahead?

Twitter Typeahead is a autocomplete/suggestion engine made for text fields on websites. As a dependency, Typeahead requires jQuery.

Typeahead with Backbone


Check the Typeahead examples and find the example that is suitable for your app's use case.


Copy the example js code and create a function in the view which is responsible for generating the form.

{% highlight js %} // ...

this.twitterTypeahead: function() { // constructs the suggestion engine var states = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'), queryTokenizer: Bloodhound.tokenizers.whitespace, // states is an array of state names defined in "The Basics" local: \$.map(states, function(state) { return { value: state }; }) });

// kicks off the loading/processing of local and prefetch states.initialize();

\$('#bloodhound .typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', displayKey: 'value', // ttAdapter wraps the suggestion engine in an adapter that // is compatible with the typeahead jQuery plugin source: states.ttAdapter() }); },

// ... {% endhighlight %}


This function should run within the view's render() function.

{% highlight js %} // ... this.redner: function() { // ... this.twitterTypeahead(); // ... }, // ... {% endhighlight %}


You need to style the typeahead drowpdown. See this stackoverflow thread for more info.

5 Optional

If you happen to use a remote source for data, use the remote example in the Twitter Typeahead example page. Also on the server side, set up routes, controller etc. for allowing the Typeahed to make calls to your server for data.