简体   繁体   中英

Typeahead.js, Searches Don't Work After Fetching Remote Data

Typeahead.js is not updating the search index after requesting remote data.

I type a query, it fetches results, and then it always displays the first N items without respect to the query. I have used the bloodhound_inst.search('lemon', sync, async) function in the console and it's returning the entire remote dataset regardless of any text match.

For example this query will return 'apple', 'pizza', anything that comes back from the server.

I am expecting it to fetch remote data and then provide search results like normal. Is it expecting the remote to provide the correct data? I am just passing a test list of items from the server ['lemon', 'banana', 'apple', 'whatever'] as the response.

<script>
  var food_name= '<%= @food.name %>';

  var food_items = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: '../food_item_search?food_name_q=%QUERY',
      wildcard: '%QUERY'
    }
  });

  var engine = food_items.initialize(true);

  $('.typeahead').typeahead(null, {
    limit: 7,
    source: food_items
  })

</script>

You guessed it. It is expecting the remote to perform the search.

If you wanted to load all the data in and then have it search that data for you, you would use local, not remote. I accomplished that like this:

ajaxGet('/manage/persontypeahead')
    .done(function (r) {
        applyNamesTypeahead(r.ViewModel);
    });

Where applyNamesTypeahead consumes the loaded data and builds the Bloodhound:

function applyNamesTypeahead(local) {
    var namesBloodhound = new Bloodhound({
        local: local,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Name')
    });

then, builds the Typeahead:

    $('#Name').typeahead({
        hint: true,
        classNames: {
            menu: 'dropdown-menu',
            suggestion: 'dropdown-item',
            cursor: 'active'
        }
    }, {
        source: namesBloodhound,
        display: 'Name'
    });

I included the classNames here to show how we're using standard Bootstrap 5 to render the Twitter Typeahead, without having to custom style it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM