使用新模型重置 Backbone 集合不会覆盖以前的模型?
Resetting Backbone collection with new models doesn't override previous models?
我想在每次收到新数据时对 Backbone 集合进行批量重置,我希望发生的情况是每次我进行重置时,所有当前模型都被清空,新数据重置为top 但我发现新数据只是作为新模型与以前的模型一起添加。任何人都可以建议我需要做什么才能实现这一目标吗?
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/
Fiddle: http://jsfiddle.net/cpbcx7nt/3/
出现了 2 个问题。
第一个问题是,当您重置集合时,您并没有重置 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
数组中的一个对象。当您更改 response
的 name
属性 时,您也在更改 data
内部的引用对象。你在第二次调用解析时看到一个额外的“+”,因为你在第一次解析中改变了 data
。
我克隆了该对象以防止意外覆盖。
const OrderModel = Backbone.Model.extend({
parse(response) {
var model = _.clone(response);
model.name = `+${response.name}`;
return model;
}
});
我想在每次收到新数据时对 Backbone 集合进行批量重置,我希望发生的情况是每次我进行重置时,所有当前模型都被清空,新数据重置为top 但我发现新数据只是作为新模型与以前的模型一起添加。任何人都可以建议我需要做什么才能实现这一目标吗?
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/
Fiddle: http://jsfiddle.net/cpbcx7nt/3/
出现了 2 个问题。
第一个问题是,当您重置集合时,您并没有重置 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
数组中的一个对象。当您更改 response
的 name
属性 时,您也在更改 data
内部的引用对象。你在第二次调用解析时看到一个额外的“+”,因为你在第一次解析中改变了 data
。
我克隆了该对象以防止意外覆盖。
const OrderModel = Backbone.Model.extend({
parse(response) {
var model = _.clone(response);
model.name = `+${response.name}`;
return model;
}
});