我希望每次收到新数据时都会在Backbone集合上进行批量重置,我希望每次进行重置时,所有当前模型都清空,新数据重置,但我发现的是新数据只是作为新模型与之前的模型一起添加。任何人都可以建议我为实现这一目标需要做些什么吗?
JS
const OrderModel = Backbone.Model.extend({
parse(response) {
response.name = `+${response.name}`;
console.log(response.name);
return response;
}
});
const OrdersCollection = Backbone.Collection.extend({
model: OrderModel,
initialize() {
setTimeout(() => {
this.trigger('snapshot', data);
}, 1000);
setTimeout(() => {
this.trigger('snapshot', data);
}, 2000);
this.listenTo(this, 'snapshot', this.setCollection, this);
},
setCollection(response) {
this.reset(response, {parse: true});
}
});
jsFiddle:http://jsfiddle.net/kyllle/cpbcx7nt/
答案 0 :(得分:2)
小提琴:http://jsfiddle.net/cpbcx7nt/3/
发生了两个问题。
第一个问题是,当您重置集合时,您没有重置html。在再次添加之前,您需要清除之前的3个列表项。
像这样:
renderRows() {
this.$el.empty()
this.collection.each(this.renderRow, this);
},
第二个问题是这段代码
const OrderModel = Backbone.Model.extend({
parse(response) {
response.name = `+${response.name}`;
return response;
}
});
参数response
引用data
数组中的对象。当您更改name
的{{1}}属性时,您还要更改response
中的引用对象。你会看到额外的" +"第二次调用是因为你在第一个解析中突变了data
。
我克隆了对象以防止意外覆盖。
data