9

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

假设我想使用车把模板来呈现我的项目。

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

我的问题是:
应该如何将 (1) 与 bootstrap-typeahead.js v2.1.0 一起使用?

这是(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);
};

(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;
    }
});

(3)

<a>{{ first_name }} {{ last_name}}</a>
4

1 回答 1

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;
};

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

于 2012-10-04T14:47:56.243 回答