如何使用把手/胡子和bootstrap typeahead来渲染项目

Lor*_*ard 9 javascript autocomplete mustache backbone.js twitter-bootstrap

我想自定义使用把手模板由bootstrap-typeahead呈现的项目.查看代码似乎是默认项目<li><a href="#"></a></li>.

我们假设我想使用把手模板来渲染我的项目.

我认为我应该以这种方式重新定义渲染功能(1).

我的问题是:
如何使用bootstrap-typeahead.js v2.1.0`中的(1)?

这是(2)关于我传递给的选项的代码$.fn.typeahead和(3)我的把手/胡子模板.


(1)

var renderItem = function (ul, user) {
    // user is the Backbone.Model
    return $('<li></li>')
        .data('item.autocomplete', user)
        .append(autocompleteItemTemplate(user.toJSON()))
        .appendTo(ul);
};
Run Code Online (Sandbox Code Playgroud)

(2)

element.typeahead({
    minLength: 3,
    source: function () {
        var users = app.userCollection;

        users = _.map(users, function (user) {
            return user.get('first_name') + ' ' + user.get('last_name');
        });
        return users;
    }
});
Run Code Online (Sandbox Code Playgroud)

(3)

<a>{{ first_name }} {{ last_name}}</a>
Run Code Online (Sandbox Code Playgroud)

小智 2

您可以像这样覆盖渲染方法:

element.data( "typeahead" ).render = function ( items ) {
    var that = this;

    that.$menu.empty();
    items = $( items ).map(function (i, item) {
        i = renderItem( that.$menu, item ).attr( "data-value", item );
        i.find( "a" ).html( that.highlighter(item) );
        return i[0];
    });

    items.first().addClass( "active" );
    return this;
};
Run Code Online (Sandbox Code Playgroud)

但是,由于 Typeahead 的 source 属性必须始终是字符串数组或返回字符串数组的函数,因此在 renderItem 函数中,用户参数将是字符串,所以我认为您将无法使用 Handlebars。