简体   繁体   中英

Showing total results count using Typeahead.js's prefetch

I'm using Typeahead.js with an implementation that looks very similar to the "multiple datasets" found in the examples :

var nbaTeams = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      prefetch: '../data/nba.json'
});

var nhlTeams = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      prefetch: '../data/nhl.json'
});

var footer = function (context) {
    // calculate total hits here
    return "<a href='...'>" + count + "</a>";
}

$('#multiple-datasets .typeahead').typeahead(null, {    
      name: 'nba-teams',
      display: 'team',
      source: nbaTeams,
      templates: {
          header: '<h3 class="league-name">NBA Teams</h3>'
      },
      limit: 3
    },
    {
      name: 'nhl-teams',
      display: 'team',
      source: nhlTeams,
      templates: {
          header: '<h3 class="league-name">NHL Teams</h3>',
          footer: footer
      },
      limit: 3
});

I'm using the latest version of Typeahead.js (v0.11.1). I'm trying to add a footer template to the bottom of the NHL teams section which has the total number of matching results. Something like <a href="...">Browse all ### results</a> . I can't find anywhere in the documentation where I can pull the count of total hits from Bloodhound.

I've seen people do this with remote data sources, but my data source is small enough to be pulled in and cached so I'd like to use prefetch.

I think your other code is perfectly fine, you just need to update your footer function with following.

var footer = function (context) {
    // calculate total hits here
    return "<a href='#'>browse all <b>" + context.suggestions.length + "</b> results</a>";
}

Look at this fiddle.

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