Callback Method for Twitter’s Typeahead

When you start using Twitter’s typea­head, e.g. because you switched from Boot­strap 2.3 to 3.0, you will notice that it is NOT a sim­ple drop-in replace­ment for Bootstrap’s orig­i­nal typea­head!
Before, you gen­er­at­ed the sug­ges­tions shown to the user by imple­ment­ing a call­back method while cre­at­ing the typea­head like this:

  source: function(query, process) { 
    ... return a list of suggestions (see doc for details) 

Since ver­sion 3, Boot­strap does not provide its own typea­head any more, instead it is using Twitter’s own imple­men­ta­tion which seems to be a good choice at least on the long run. But it does not provide any mean for defin­ing a call­back method to provide the sug­ges­tions — no clue why.
Instead you can provide a pre­de­fined array local­ly, a pre­de­fined array that will be load­ed on start-up, or a remote ser­vice defined by a URL.
You will find sev­er­al good exam­ples of why you need a call­back method some­times.

  • You want/have to use a Javascript library to access the ser­vice.
  • There is no data­base for the sug­ges­tions, they a gen­er­at­ed on the fly, e.g.if you want to sug­gest sen­tence com­ple­tion while the user types.
  • You are using Meteor’s col­lec­tions hold­ing your sug­ges­tions, thus, there is no URL you could point to.

But tak­ing a look into the inter­nals revealed fol­low­ing solu­tion: com­plete­ly by-pass the inter­nal sug­ges­tion aggre­ga­tion of Twitter’s typea­head by replac­ing the getSuggestions(query, callback) method of the first dataset, which we defined by local: [];.

(t = $("field")).typeahead({ local: [] });"ttView").datasets[0].getSuggestions = function(query, callback) {
  var suggestions = ... gather your suggestions here ...
  var data = [];
  for (suggestion in suggestions) { data.push(this._transformDatum(suggestion)); }

(Trans­lat­ed from Cof­fee­script on-the-fly — con­sid­er as a draft than an out-of-the-box solu­tion.)

Hap­py hack­ing. 🙂

p.s. for Mete­or users: The call­back breaks each time the tem­plate gets re-ren­dered — despite that you use the pack­age preserve-inputs or <#constant> due to a bug. Some­how, con­stant areas and that par­tic­u­lar pack­age do not get along with each oth­er. Solu­tion: removed the pack­age and use con­stant areas around typea­head input fields works. This should be fixed as soon as the new tem­plate engine gets rolled out.

One Reply to “Callback Method for Twitter’s Typeahead”

Leave a Reply

Your email address will not be published. Required fields are marked *