讓我們假設您的HTML頁面中有一個表格,其中id="employee"
已被定義爲template
,對應於表格中的一行。爲簡單起見,我們asssume員工行只是有firstname
和lastname
:
<table id="employee">
<thead>
<tr><td>Firstname</td><td>Lastname</td></tr>
</thead>
<tbody>
</tbody>
</table>
<script type="text/template" id="employee-template">
<td><%= firstname %></td><td><%= lastname %></td>
</script>
需要兩個views
一個渲染表,以及一個呈現在表的每一行。它們可能如下所示:
//a (table) view to render the list of employees
var employee_list_view = Backbone.View.extend({
el: $('#employee'),
initialize: function() {
this.collection.bind("add", this.render, this);
},
//this creates new rows in the table for each model in the collection
render: function() {
_.each(this.collection.models, function(data) {
this.$el.append(new employee_view({
model: data
}).render().el);
}, this);
return this;
}
});
//a (row) view to render each employee
var employee_view = Backbone.View.extend({
tagName: "tr",
template: _.template($("#employee-template").html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
從服務器獲取集合後,項目將存儲在集合中。您可以使用以下代碼查看檢索到的數據。成功時,我們創建一個新的員工列表(本例中爲表)並傳遞員工集合。
var employee = new EmployeeCollection();
employee.fetch({
success: function() {
console.log(employee.toJSON());
new employee_list_view({collection: employee}).render();
},
error: function() {
console.log('Failed to fetch!');
}
});
注意:建議使用成功/失敗回調。
看看這個working version on JSFiddle
'_.each(this.collection.models,...'可能是因爲['this.collection.each(...)'(HTTP更好:/ /backbonejs.org/#Collection-Underscore-Methods)。你不想'this。$('tbody')。append(...)'添加'employee_view's嗎? –
感謝您的評論!猜,我正在學習很多參與Q/A的東西。乾杯:) –