Typeahead.js substringMatcher函数的说明

Jav*_*bra 3 javascript typeahead.js

我正在做一些研究Typeahead.js,这是一个非常酷的库。多亏了文档,我已经设法得到一个基本的示例,它也非常好。

但是,我试图弄清楚下面的代码块实际在做什么?

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)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};
Run Code Online (Sandbox Code Playgroud)

在该示例中,它是在初始化预输入时作为source选项传递的。我可以理解,它是从文本框中取输入并将其与数据集,但我很困惑,一个多小的q和cb是谁?

Jon*_*ink 5

q是要搜索的值。这被传递到正则表达式匹配器中,并且搜索不区分大小写(“ i”参数)

cb 是回调函数,它返回从搜索中找到的匹配项。

findMatches基本上是一个匿名函数,用作该substringMatcher函数的实现。