我是backbone.js 世界的新手。我想使用backbone.js与服务器通信并将员工详细信息呈现到表中。我使用以下代码从服务器获取数据:
var EmployeeCollection = Backbone.Collection.extend({
model: Person,
url:"http://localhost:4000/get/employee",
parse : function(res)
{
console.log('response inside parse' + res);
return res;
}
});
var employee = new EmployeeCollection();
employee.fetch();
在日志语句中,我得到:解析[object Object]、[object Object]、[object Object]内的响应
但我不知道接下来会发生什么。如何从我正在获取的对象中检索数据并将其呈现到表上。有人有建议吗?
最佳答案
假设您的 HTML 页面中有一个带有 id="employee"
的表格,并且您已经定义了与表格中的一行相对应的模板
。为简单起见,我们假设员工行只有 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>
您需要两个 View
,一个用于呈现表格,另一个用于呈现表格中的每一行。它们可能看起来像:
//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!');
}
});
注意:建议使用成功/失败回调。
关于javascript - 从数据库获取数据并将其呈现到backbone.js中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13137796/