【问题标题】:how to use handlebars/mustache and bootstrap typeahead for rendering item如何使用车把/小胡子和引导输入来渲染项目
【发布时间】:2012-10-04 22:47:56
【问题描述】:

我想自定义由 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>

【问题讨论】:

    标签: javascript backbone.js autocomplete twitter-bootstrap mustache


    【解决方案1】:

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

    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 的 source 属性必须始终是字符串数组或返回字符串数组的函数,因此在 renderItem 函数中用户参数将是字符串,所以我认为您将无法使用 Handlebars。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多