使用Typeahead.js的预取显示总结果数

Dyl*_*rry 6 javascript typeahead.js bloodhound

我正在使用Typeahead.js,其实现看起来与示例中的"多个数据集"非常相似:

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
});
Run Code Online (Sandbox Code Playgroud)

我正在使用最新版本的Typeahead.js(v0.11.1).我正在尝试将一个页脚模板添加到NHL团队部分的底部,该部分具有匹配结果的总数.有点像<a href="...">Browse all ### results</a>.我在文档中找不到任何可以从Bloodhound中获取总命中数的地方.

我见过人们使用远程数据源来做这件事,但我的数据源很小,可以被拉入和缓存,所以我想使用预取.

Rav*_*iya 3

我认为你的其他代码非常好,你只需要使用footer以下内容更新你的函数。

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

看看这个小提琴。