Question

I'm trying to get Twitter Typeahead+Bloodhound to work with Google's CSE.

So far, I've managed to get the results returning, but I'm not able to work out the datumTokenizer.

var results = new Bloodhound({
  datumTokenizer: function(data) {
   return Bloodhound.tokenizers.whitespace(d.value)
  },
  queryTokenizer: Bloodhound.tokenizers.obj.whitespace,
  remote: {
    url: "http://clients1.google.com/complete/search?client=partner&hl=en&sugexp=gsnos%2Cn%3D13&gs_rn=25&gs_ri=partner&partnerid=004914516364918182382%3Ayfqw09r4qvu&types=t&ds=cse&cp=3&gs_id=15&q=%QUERY&callback=showResults&duffCallback=?",
    ajax: $.ajax({type:'GET',dataType:'jsonp',jsonp:'duffCallback'}),
    filter: showResults
  }
});

See the fiddle: http://jsfiddle.net/thugsb/3KAjh/

You'll see that I've got the results being returned from showResults() as an array. However, the call to showResults() from the filter: doesn't seem to be doing anything, as removing that line has no effect. So I'm not quite sure what is going on.

Note the duffCallback is what I worked out to do from reading this question. If there's a better way to make this work I'm all ears!

Was it helpful?

Solution

Firstly the datumTokenizer you were using was not quite right. You need to change it to:

datumTokenizer: function(data) {
 return Bloodhound.tokenizers.whitespace(data.value)
}

Note how the "whitespace" function is now referencing the "data" input parameter instead of "d" which you were using.

As for a a solution to your problem, see it working here (for example try searching for "athletics"):

http://jsfiddle.net/Fresh/FYavC/

The main problem with your code was in your remote URL (and this had me confused too!). The offending query string parameters are:

...&callback=showResults&duffCallback=?

"duffCallback=?" is not required as specifying "datatype:'jsonp'" in the ajax object automatically adds the callback details (i.e. "?callback=?") used by the jsonp request. Also the "callback=showResults" is not required as the filter method is implicitly called by the Bloodhound framework when a successful jsonp request is made.

I agree that it's not obvious on how remote calls should be made when using Typeahead.js. An example of a remote call where the ajax object is specified and some documentation would be useful on Typeahead.js website!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top