如何使用twitter typeahead中的把手绑定动态元素属性

时间:2014-11-23 20:42:56

标签: javascript jquery handlebars.js typeahead

我正在使用twitter typeahead处理自动完成代码段,需要修改模板。问题是我想使用handlebarjs模板引擎动态地将类名绑定到模板。我的代码到目前为止:

var terms = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace("title"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        remote: {
            // url points to a json file that contains an array of country names, see
            // https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
            url: '/results?q=%QUERY&r=all',
            // the json file contains an array of strings, but the Bloodhound
            // suggestion engine expects JavaScript objects so this converts all of
            // those strings
            filter: function (data) {
                return $.map(data, function (val, i) {
                    return {
                        title : val._source.title,
                        address : val._source.address,
                        type : val._type
                    };
                });
            },
            ajax :{
                type:"GET"
            }
        }
    });

    // kicks off the loading/processing of `local` and `prefetch`
terms.initialize();
$("#search-input").typeahead({
        highlight: true,
        hint:false
    }, {
        name: 'terms',
        displayKey: 'title',
        // `ttAdapter` wraps the suggestion engine in an adapter that
        // is compatible with the typeahead jQuery plugin
        source: terms.ttAdapter(),
        templates:{
            header:Handlebars.compile([
                '<div class="list-group">'
            ].join('')),
            suggestion:Handlebars.compile([
                    '<a href="#" class="list-group-item">',
                        '<div class="type-{{type}} pull-right"></div>',//here it doesn't echo type-article,type-doctor,...
                        '<h4 class="list-group-item-heading">{{title}}</h4>',
                        '<p class="list-group-item-text">{{address}}</p>',
                    '</a>'
            ].join('')),
            footer:Handlebars.compile([
                '</div>'
            ].join(''))
        }

    });

我在评论部分有问题。谢谢你的帮助。

0 个答案:

没有答案