【发布时间】:2014-03-03 18:18:24
【问题描述】:
我是 Backbone.js 的一个完整的 n00b,并且只使用了几天。我正在尝试获取 JSON 数据来填充模型,在这种情况下,我需要生成两个模型。这是我一直在使用的示例 JSON:
JSON
{
"status": "200",
"total": "2",
"items":
[{
"id": "1",
"name": "Here is another name",
"label": "Label for test",
"description": "A description for more information.",
"dataAdded": "123456789",
"lastModified": "987654321"
},
{
"id": "2",
"name": "Name of item",
"label": "Test Label",
"description": "This is just a long description.",
"dataAdded": "147258369",
"lastModified": "963852741"
}]
}
主干 JS
// MODEL
var Service = Backbone.Model.extend({
defaults: {
id: '',
name: '',
label: '',
description: '',
dateAdded: '',
dateModified: ''
}
});
var service = new Service();
// COLLECTION
var ServiceList = Backbone.Collection.extend({
model: Service,
url: "./api/service.php",
parse: function(response) {
return response.items;
}
});
//
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
success: function() {
console.log("Working!");
console.log(serviceList.length);
},
error: function() {
console.log("Failed to fetch!");
}
});
// VIEW for each Model
var ServiceView = Backbone.View.extend({
el: $('.widget-content'),
tagName: 'div',
template: _.template($('#service-template').html()),
initialize: function() {
this.collection.bind("reset", this.render, this);
},
render: function() {
console.log(this.collection);
this.$el.html('');
var self = this;
this.collection.each(function(model) {
self.$el.append(self.template(model.toJSON()));
});
return this;
}
});
//
var serviceView = new ServiceView({
collection: serviceList
});
console.log(serviceView.render().el);
html
<div class="widget-content">
<!-- Template -->
<script type="text/template" id="service-template">
<div><%= name %></div>
</script>
</div>
当我在控制台记录 serviceList.length 时,我得到的值为 2,因此我相信 JSON 对象已成功获取。我也得到了“工作!”对成功的回应也是如此。但是,在视图中,我显示的是一个空对象,这给了我一个空模型。
我仍在尝试了解执行此操作的最佳方法。也许我应该为“项目”使用集合,然后为每个模型数据映射集合?我究竟做错了什么?非常感谢任何建议或帮助。
【问题讨论】:
标签: json backbone.js model render