Typeahead.js 0.10.x:如何显示每个类别的结果数

dro*_*sen 5 typeahead.js twitter-typeahead

Typeahead.js 0.10支持页眉和页脚以及搜索结果的模板.我希望能够获得每个类别的实际结果/建议数(即忽略限制值)并在类别名称标题中显示.

例如 -

结果:

  • A类(24结果)
    • -A1
    • -A2
    • -A3
  • B类(167结果)
    • -B1
    • -B2
    • -B3

我的模板目前看起来像这样:

{
name: 'Applications',
displayKey: 'value',
source: app.ttAdapter(),
extraVars:Handlebars.registerHelper("numResults",function(){
    return (  "HowToGetTheseResults??" );
}),
templates: {
    header:Handlebars.compile([
        '<h3 class="applications"> Applications ({{numResults}}) results  </h3>'
    ].join('')),

    suggestion: Handlebars.compile([
        '<p><b>{{value}}</b> </p>'
    ].join(''))
}
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以提前输入结果/建议的数量?我确定typeahead对象(或者是bloodhound对象?)必须在某个地方存储这些数据.

dte*_*eri 6

您可以定义自己的函数来处理用户输入的查询.

我做了一个样本小提琴:http://jsfiddle.net/dtengeri/6ApJg/

基本的想法是你手动从Bloodhound引擎获得建议,并只将所需数量的结果传递给typeahead.

// Custom source function in the dataset definition.
source: function (query, cb) { 
  // Get the data from the Blodhound engine and process it.
  nbaTeams.get(query, function (suggestions) {
    // Show only the first 3 results.
    cb(suggestions.slice(0, 3));
    // Set the headers content.
    $('#nba-header').text(suggestions.length);
  })
},
Run Code Online (Sandbox Code Playgroud)

您必须在标题模板中定义一个HTML元素,您将在其中放置结果数.(此示例中带有id#nba-header的范围.)

templates: {
  // Insert an HTML element where you will place the number of results.
  header: '<h3 class="league-name">NBA Teams (<span id="nba-header"></span>)</h3>'
}
Run Code Online (Sandbox Code Playgroud)

为了获得所有结果,您应该在Bloodhound引擎中设置一个高数字作为限制:

var nbaTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: nba(),
  limit: Number.MAX_VALUE // Set the limit as high as possible.
});
Run Code Online (Sandbox Code Playgroud)