6

希望这不是重复:为什么 Bloodhound.get() 返回未定义?

我升级到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/

任何想法为什么会发生这种情况?

4

2 回答 2

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" />

摆弄上述修复:

提琴手

于 2014-02-08T19:52:51.170 回答
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;
        }
    }
});
于 2015-01-23T14:44:44.207 回答