为什么typeahead建议未定义?

时间:2014-02-08 17:21:50

标签: typeahead typeahead.js bloodhound

希望这不是重复:Why does bloodhound.get() return undefined?

我升级到 typeahead.js版本0.10.0 。以前的版本正确地返回了建议。现在我收到undefined返回以下代码:

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

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

$('#typeahead').typeahead(null, {
        source: engine.ttAdapter()
    });

这是我的小提琴:http://jsfiddle.net/ucUcn/6/

为什么会发生这种情况?

2 个答案:

答案 0 :(得分:9)

local数组必须包含对象,而不是自己的字符串。

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

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

$('#typeahead').typeahead(null, {
  displayKey: 'd',
  source: engine.ttAdapter()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<input id="typeahead" />

摆弄上述修复:

JsFiddle

答案 1 :(得分:1)

正如@Chad所说,结果数组必须包含对象。

我只想添加用于显示建议的默认值为value

所以你可以做类似

的事情
var suggestionEngine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "myUrl",
        filter: function (suggestions) {
            var mappedResult = $.map(suggestions[1], function(suggestion) {
                return { value : suggestion }
            });

            return mappedResult;
        }
    }
});