【问题标题】:twitter typeahead.js process() populates list with undefinedstwitter typeahead.js process() 使用未定义填充列表
【发布时间】:2014-04-25 17:16:57
【问题描述】:

我似乎和Twitter Typeahead Ajax results undefined有同样的问题,但一直没有解决,所以我再次询问,希望我能提供一些缺失的细节。

我正在使用独立的 typeahead 0.10.2 和 bootstrap 2.3.1。下划线是 1.6.0。包含的库的完整列表是:

<script src="/static/portal/js/jquery-1.9.1.min.js"></script>
<script src="/static/portal/js/jquery-ui-1.10.2.custom.min.js"></script>
<script src="/static/portal/js/bootstrap.min.js"></script>
<script src="/static/portal/js/typeahead.bundle.min.js"></script>
<script src="/static/portal/js/hogan-2.0.0.min.js"></script>
<script src="/static/portal/js/underscore-min.js"></script>

在我的第一次尝试中,我以http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead 为脚本建模,一切似乎都正常,直到调用 process()。而不是用我的结果填充自动建议下拉列表,它只包含“未定义”值(尽管元素数量正确)。

$("#create_track").click(function() {
    var names_id_map = {};
    $('#ul_results').addClass('hide');
    $('#create_track_form').removeClass('hide');
    // use debounce from underscore.js to throttle requests to server
    var suggestArtists = _.debounce(function(query, process) {
        var artist_names = [];
        $.get(ARTIST_NAMES_URL, { q: query }, function (data) {
            // data = {"results": [{"id": "artist_123", "name": "xyz"}, ...]}
            $.each(data, function (key, val) {
                if (key == "results") {
                    $.each(val, function (i, item) {
                        artist_display = item.name + ' - ' + item.id;
                        artist_names.push(artist_display);
                        names_id_map[artist_display] = item.id;
                    });
                }
            });
            process(artist_names);
        });
    }, 300); // rate limit requests to server

    $("#artist_name").typeahead(null, {
        name: 'artist-names',
        minLength: 1,
        source: function (query, process) {
            suggestArtists(query, process);
        },
        updater: function (item) {
            console.dir('updater: ' + item); // never output
            $("#artist_id").val(names_id_map[item]);
            // return value which should be selected in drop-down
            // return item;
        },
    });

    return false;
});

那个特定的教程可能是为旧的 bo​​otstrap-bundled 版本的 typeahead 创建的。使用较新的独立版本 typeahead 的文档,我想出了这个,它的行为相同,从而产生了正确数量的未定义菜单:

$("#create_track").click(function() {
    var names_id_map = {};
    $('#ul_results').addClass('hide');
    $('#create_track_form').removeClass('hide');

    var artistNames = new Bloodhound({
        name: 'artist-names',
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: ARTIST_NAMES_URL + '?q=%QUERY',
            //rateLimitBy: debounce, // debounce is not defined?
            rateLimitWait: 300,
            filter: function(data) {
                var artist_names = [];
                // data = {"results": [{"id": "artist_123", "name": "xyz"}, ...]}
                $.each(data, function (key, val) {
                    if (key == "results") {
                        $.each(val, function (i, item) {
                            artist_display = item.name + ' - ' + item.id;
                            artist_names.push(artist_display);
                            names_id_map[artist_display] = item.id;
                        });
                    }
                });
                return artist_names;
            },
        }
    });
    artistNames
        .initialize()
        .done(function() { console.log('artistNames init success'); });

    $("#artist_name").typeahead(null, {
        minLength: 1,
        source: artistNames.ttAdapter(),
    });

    return false;
});

如果我用这样的本地数据填充它:

$("#create_track").click(function() {
    var names_id_map = {};
    $('#ul_results').addClass('hide');
    $('#create_track_form').removeClass('hide');

    var artistNames = new Bloodhound({
        name: 'artist-names',
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: ["Abc", "Def", "Ghi", "Jkl"],
    });
    artistNames.initialize()
        .done(function() { console.log('artistNames init success'); });

    $("#artist_name").typeahead(null, {
        minLength: 1,
        source: artistNames.ttAdapter(),
    });

    return false;
})

例如,我可以输入“a”或“d”,然后得到一个“未定义”的建议。键入“b”、“c”或“z”不会给出任何建议。

在过去的一天里,我已经阅读了有关 Google 和 SO 上的 typeahead 的所有信息。我相信我的 JSON 已正确解码,并且在所有情况下,我的艺术家名称都是原生 JS 字符串数组。

【问题讨论】:

  • 请输入您自己的答案作为答案并接受

标签: javascript jquery ajax twitter-bootstrap typeahead.js


【解决方案1】:

https://github.com/twitter/typeahead.js/blob/master/doc/bloodhound.md#api 的示例重新开始(并由另一个重复的Why does bloodhound.get() return undefined? 提示),我意识到我的本地值数组实际上需要是与 datumTokenizer 和 typeahead 合作的哈希/字典显示键。我现在有一个简单的示例,用于处理单前导字母建议:

var artistNames = new Bloodhound({ 
    name: 'artist-names',
    datumTokenizer: function (d) { return d.d; },
    queryTokenizer: Bloodhound.tokenizers.whitespace, 
    local: [{"d": "Abc"}, {"d": "Aaa"}, {"d": "Aab"}, {"d": "Def"}, {"d": "Ghi"}, {"d": "Jkl"}, {"d": "John Coltrane"}], 
}); 
artistNames.initialize().done(function() { alert('setup ok'); });

$("#artist_name").typeahead(null, { 
    minLength: 1, 
    displayKey: "d",
    source: artistNames.ttAdapter(), 
});

我最初的语法来自我通过谷歌找到的一些教程,这些教程可能使用了旧的引导版本的库(例如,来自我链接到这篇文章的@顶部的那个:“然后一个简单的名称数组 (['John Smith','Jane Smith',...]) 被传递给 process() 回调。")。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多