Ir1sh Ir1sh - 7 months ago 84
Javascript Question

jquery select2 with bloodhound.js suggestion engine

I am using the angular-ui selector2 wrapper tom implement some tagging like functionality.

I use bloodhound in other areas of the site for typeahead suggestions and I have a bloodhound engine already initialised for the data set I want to hit use with select2.

I just can't grok the docs on how to use the select two query option to access the data through bloodhound instead of ajax

Does anyone have an example of these two libraries working together?

Answer

I recently had to do this in a Marionette context, but it shouldn't differ much with angular since we're only dealing with javascript. You'll need to do 2 things to make twitter bloodhound compatible with select2.

  1. In select2's query method, call your bloodhound engine's get method and pass it the search term and a callback. Bloodhound will call this cb and pass it an array of result objects. Select2 wants this array wrapped in an object, like this {results: bloodHoundArray} so your cb needs to do the data wrapping.
  2. Make sure your bloodhound's prefetch or remote configuration has a filter function that maps raw results into an object with at least an id and a text field, because that's what select2 relies on.

Here is an example to make things clearer:

var engine = new Bloodhound({
      prefetch:{
          url: someUrl,
          filter: function(response){
              return _.map(response.results, function(obj){return {id:obj.tag, text:obj.tag};});
          }
      },  
   });
engine.initialize();
$('#elem').select2({quietMillis:300,
                 query: function (query) {
                     engine.get(query.term, function(resultArr){
                         query.callback({results:resultArr});});
                 }
 });
Comments