Why Twitter Typeahead Fails You When Working With Real Data

Noting this because it has been hurting me like broken glass in a straw for days. Twitter Typeahead works great in the examples but breaks horribly when I use it against real data.  Why?

Consider the following super easy example form the twitter site(http://twitter.github.io/typeahead.js/examples/):

      <div class="content">
        <h2>Countries</h2>
        <p>Prefetches data, stores it in localStorage, and searches it on the client</p>

        <div>
          <input type="text" class="typeahead" placeholder="countries">
        </div>

        <div>
          <script src="https://gist.github.com/jharding/4983527.js"></script>
        </div>
      </div>

First, implementing this on a local web server, you have to deal with the cross-site issues with the second nested DIV that incorporates the off-site javascript.  This probably won’t work still because it requires another cross-site bit of communication found in examples.js.

I have a Countries table but it is full of other data, offered up simply in Java(Grails) as Render as JSON.  Should be fine, but–surprise, surprise, surprise–it isn’t.  After much trying the following I could get one and only one row returned (TIP: Watch those classes).

$(document).ready(function() {
 $('.content .typeahead').typeahead({
   remote: 'http://myserver.com/data/Countries.json',
   template: [
     '<p class="language">{{language}}</p>',
     '<p class="name">{{countryAbbr}}</p>',
     '<p class="description">{{description}}</p>'
   ].join(''),
   engine: Hogan
 });
});

Finally, there is a seldom documented keyword keyValue.  That is to say I haven’t found the documentation to cover it. Use it to identify your uniqueness.

$(document).ready(function() {
 $('.content .typeahead').typeahead({
   remote: 'http://myserver.com/data/Countries.json',
   keyValue: 'countryName',
   template: [
     '<p>{{language}}</p>',
     '<p>{{countryAbbr}}</p>',
     '<p>{{description}}</p>'
   ].join(''),
   engine: Hogan
 });
});

And that, my friends is why you can’t get what you expect out of the typeahead with your real JSON data for real tables. Typeahead needs to know where to find uniqueness and that makes sense.

Should I find more documentation I will post it.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.