为什么bloodhound.get()返回undefined?

时间:2014-02-05 23:43:00

标签: jquery typeahead typeahead.js bloodhound

我正在尝试使用下面的代码与typeahead.js v 0.10

// instantiate the bloodhound suggestion engine
var numbers = new Bloodhound({
datumTokenizer: function(d) { return d; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local:  ["(A)labama","Alaska","Arizona","Arkansas"]
});

// initialize the bloodhound suggestion engine
numbers.initialize();
console.log(numbers.get('a'));

事实上我试着解决这个问题:https://github.com/bassjobsen/Bootstrap-3-Typeahead/issues/26 我期望下面显示的内容应该是可能的:

 $('.typeahead').typeahead(
{
items: 4,
source:function(query){return numbers.get(query)}       
});

更新

examples。使用ttAdapter()设置typeahead的来源。 此函数还可用于为Bootstrap-3-Typeahead设置source属性(接受字符串数组或函数):

// instantiate the bloodhound suggestion engine
var numbers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,//function(d) { return d; },
queryTokenizer: Bloodhound.tokenizers.whitespace,
local:  ["(A)labama","Alaska","Arizona","Arkansas","Arkansas2","Barkansas"]
});

// initialize the bloodhound suggestion engine
numbers.initialize();

$('.typeahead').typeahead(
{
items: 4,
source:numbers.ttAdapter()  
});

bloodhound.js显示:

  ttAdapter: function ttAdapter() {
                return _.bind(this.get, this);
            }

所以ttAdapter()返回一个函数(get()),该函数可以由source设置,该查询作为参数。

1 个答案:

答案 0 :(得分:2)

我按如下方式实现了Bloodhound.get()(另见这个小提琴:http://jsfiddle.net/Fresh/HS9Wy/):

// instantiate the bloodhound suggestion engine
var numbers = new Bloodhound({
    datumTokenizer: function (d) {
        return d;
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: ["(A)labama", "Alaska", "Arizona", "Arkansas"]
});

// initialize the bloodhound suggestion engine
numbers.initialize();

// Get an array of datums which satisfy the query for 'a'
numbers.get('a', function (suggestions) {
    jQuery.each(suggestions, function (index, item) {
        console.log(item);
    });
});

你打电话给“get()”的问题,即

numbers.get('a')

当你得到Bloodhound执行'a'的查询时,你没有对结果做任何事情。要指示“get()”执行一些有用的操作,您需要将结果发送到输出函数。请参阅documentation here