Bloodhound.js: Transform the data returned by a remote source?

Richard picture Richard · Apr 27, 2015 · Viewed 8.4k times · Source

I am using Bloodhound with a remote API and I need to transform the result returned from the remote API.

The API URL is https://www.googleapis.com/books/v1/volumes?q=quilting which returns an object with an items property that is a list. I need to return that list to Typeahead, rather than the top-level object.

The Bloodhound docs say that there is a transform function that is supposed to do this, but I can't get it to work.

Here is my code:

var books = new Bloodhound({
  datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.num); },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: 'https://www.googleapis.com/books/v1/volumes?q=quilting'
  },
  transform: function(response) {
    console.log('transform', response);
    return response.items;
  }
});
books.initialize();

// instantiate the typeahead UI
$('#myTextBox').typeahead(null, {
  displayKey: function(suggestion) {
    console.log('suggestion', suggestion);
    return suggestion.volumeInfo.title + suggestion.volumeInfo.publishedDate;
  },
  source: numbers.ttAdapter()
});

And a JSFIddle here: http://jsfiddle.net/2Cres/46/

This does not work, because I need to feed the items list into the typeahead UI, but this doesn't seem to be happening.

Answer

skazska picture skazska · Apr 27, 2015

Try moving transform inside the remote option, like this:

remote {
  url:"fdsfds",
  transform: function (response){...}
}