typeahead.js自动完成中的源是什么,源包含什么?

时间:2014-06-19 07:47:12

标签: javascript jquery handlebars.js typeahead.js twitter-typeahead

我是typeahead.js的新手,我在这里做自动完成。问题是这里应该是什么来源,它返回什么,这里把手的功能是什么。

HTML

<div id="custom-templates">
<input class="typeahead" type="text" placeholder="Oscar winners for Best Picture"/>
</div>

脚本

$('#custom-templates .typeahead').typeahead(null, {
name: 'best-pictures',
displayKey: 'value',
source: bestPictures.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any Best Picture winners that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
}
});

我刚从twitter上学习这个例子,但是它的来源是什么以及如何将它传递给车把? 如果源是jsondata如何呈现它?

1 个答案:

答案 0 :(得分:1)

source是一个在模式更改时调用的函数(即,当用户编辑文本字段时),并且应返回匹配数组。

以下是匹配字符串数组中子字符串的源示例:

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        // the typeahead jQuery plugin expects suggestions to a
        // JavaScript object, refer to typeahead docs for more info
        matches.push({ value: str });
      }
    });

    cb(matches);
  };
};

要使用它:

source: substringMatcher(['Alabama', 'Alaska', 'Arizona', 'Arkansas'])

相关: