9

我想自定義由bootstrap-typeahead使用車把模板呈現的項目。 看看代碼,它似乎默認項目是<li><a href="#"></a></li>如何使用車把/鬍子和引導程序提前打印項目

讓我們假設我想使用一個把手模板來呈現我的物品。

我認爲我應該用這種方式重新定義渲染函數(1)。

我的問題是:
應該如何使用(1)with 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> 

回答

2

可以覆蓋render方法是這樣的:

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

然而,由於事先鍵入的內容的源屬性必須始終是一個字符串數組或返回字符串數組的功能,在renderItem功能的用戶參數將是字符串,所以我認爲你將無法使用Handlebars。