Search code examples
typeahead.jsbloodhound

How do I reference the string being queried when defining sorter function of Bloodhound object? All my data is local


Here is a code snippet:

        var bloodhound_obj = new Bloodhound({
           datumTokenizer: function(data) {
              var name = Bloodhound.tokenizers.whitespace(data.name);
              var id = Bloodhound.tokenizers.whitespace(data.id);
              return id.concat(name);
           },
           queryTokenizer: Bloodhound.tokenizers.whitespace,
           sorter: function(a, b) {
              if (a.id < b.id) {
                 return -1;
              }
              else if (a.id > b.id) {
                 return 1;
              }
              else return 0;
           },
           local: _data,
           limit: 10
        });
        bloodhound_obj.initialize();

        $("#autocomplete").typeahead({
           hint: false,
           highlight : true
        }, {
           displayKey: function(d) {
              return d.name + " (" + d.id + ")";
           },
           source: bloodhound_obj.ttAdapter(),
        });

As it stands the suggestions are sorted by "id" and I would like to change it so that the sort is dependent on my query. I have tried including a $("#autocomplete").typeahead("val") (within the sorter function) but this is slow and seems like overkill for the problem at hand.


Solution

  • The way I overcame the performance issue is.

    1. Add a 'keyup' handler for the typeahead.
    2. In this handler grab the current search criteria rather than in each call to the sorter.

    Something like:

    var key = "";
    
    $("#autocomplete").on('keyup', function(e) {
      key = $("#autocomplete").typeahead("val");
    });
    

    Now use key in your sorter function. key will only be updated on changes, not on each call to sort.