Backbone collection: 为物品模型添加逻辑
Backbone collection: add logic to item models
我使用 reset
:
从裸数组 objects 更新了 Backbone collection
const collection = new Backbone.Collection();
// ...
const switches = [
{ color: "red", on: false },
{ color: "green", on: false },
{ color: "blue", on: true }
];
collection.reset(switches);
现在我的 collection 中有 3 个模型。我希望他们有 toggle()
方法:
toggle: function() {
this.save({ on: !this.get("on") })
}
如何添加?
当您不将模型传递给 backbone 集合时,backbone 使用普通模型。如果你想有一个自定义的模型,你应该使用 Backbone.Model.extend()
函数定义一个模型并将它传递给集合:
const Model = Backbone.Model.extend({
toggle: function() {
this.save({ on: !this.get("on") })
}
});
const Collection = Backbone.Collection.extend({
model: Model
});
const collection = new Collection();
我使用 reset
:
const collection = new Backbone.Collection();
// ...
const switches = [
{ color: "red", on: false },
{ color: "green", on: false },
{ color: "blue", on: true }
];
collection.reset(switches);
现在我的 collection 中有 3 个模型。我希望他们有 toggle()
方法:
toggle: function() {
this.save({ on: !this.get("on") })
}
如何添加?
当您不将模型传递给 backbone 集合时,backbone 使用普通模型。如果你想有一个自定义的模型,你应该使用 Backbone.Model.extend()
函数定义一个模型并将它传递给集合:
const Model = Backbone.Model.extend({
toggle: function() {
this.save({ on: !this.get("on") })
}
});
const Collection = Backbone.Collection.extend({
model: Model
});
const collection = new Collection();