从网址填充Backbone集合后,我遇到了模型消失的问题。如果我只是将数组传递给集合,代码就可以工作。
收藏品:
var CustomerList = Backbone.Collection.extend({
model: Customer,
url: "/customer_list/json"
});
网址返回:
[
{
"id":"870000",
"name":"vitae odio",
"contact_name1":"ame",
"contact_number1":"345634565246",
"contact_name2":"",
"contact_number2":"",
"address_line1":"Ap #489-8375 Ornare, Ave2",
"address_line2":"",
"town":"Stillwater",
"county":"Herefordshire",
"postcode":"JV5H 2QH",
"email":"parturient@vitae.edu",
"created_at":"0000-00-00 00:00:00",
"updated_at":"2012-08-18 16:44:36"
},
{
"id":"870001",
"name":"mauris, aliquam",
"contact_name1":"Quail",
"contact_number1":"82733186940",
"contact_name2":null,
"contact_number2":null,
"address_line1":"Ap #921-368 Cras Ave",
"address_line2":null,
"town":"Lake Charles",
"county":"Essex",
"postcode":"AP6 0KZ",
"email":"vitae.dolor@Quisque.edu",
"created_at":"0000-00-00 00:00:00",
"updated_at":"0000-00-00 00:00:00"
}
]
观点:
$(function() {
/* Customer View */
var CustomerView = Backbone.View.extend({
tagName: 'tr',
className: 'customer-row',
template: _.template($('#customerRowTemplate').html()),
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this.el;
}
});
/* Customer List View */
var CustomerListView = Backbone.View.extend({
el: $('#customers'),
initialize: function() {
this.collection = new CustomerList();
this.collection.bind('reset', this.render());
this.collection.fetch();
},
render: function() {
console.log(this.collection);
console.log(this.collection.models);
_.each(this.collection.models, function(customer) {
this.renderCustomer(customer);
}, this);
},
renderCustomer: function(customer) {
var customerView = new CustomerView({
model: customer
});
var html = customerView.render();
this.$el.find('#customer-list').append(html);
}
});
var customerList = new CustomerListView();
});
调用console.log(this.collection)时;它显示模型数组的长度为366,我可以在检查器中查看所有模型。
但是在调用console.log(this.collection.models)时;它返回一个空数组。这意味着集合不会迭代,因此永远不会呈现。如果我只是手动传入客户列表,这也可以正常工作。
非常感谢任何帮助。
答案 0 :(得分:1)
问题在于:this.collection.bind('reset', this.render());
this.render()
应为this.render
。在集合有机会获取模型之前,使用括号在现场调用函数。
您还应该将上下文传递给render
函数。这可以通过两种方式完成:
_.bindAll(this, "render")
添加到CustomerListView initialize
方法。this.collection.bind('reset', this.render, this)
- 添加this
作为第三个参数。修改强>
对于0.9.9及更高版本,请使用this.listenTo(this.collection, 'reset', this.render)
答案 1 :(得分:1)
您无需使用Backbone绑定任何内容。它正确地在引擎盖下使用不需要的核心。您没有正确使用每种方法。
此外,如果要绑定操作,则必须使用函数名称,而不是执行它:
this.collection.bind('reset', this.render);
而不是
this.collection.bind('reset', this.render());
我也会尝试:
initialize: function() {
this.collection = new CustomerList();
this.collection.fetch();
},
render: function() {
console.log(this.collection);
console.log(this.collection.models);
this.collection.each(function(customer) {
this.renderCustomer(customer);
});
}
你想要'重置'到底是什么?绑定函数不在Backbone API中。你是说'开'了吗?