我使用reset
:
const collection = new Backbone.Collection();
// ...
const switches = [
{ color: "red", on: false },
{ color: "green", on: false },
{ color: "blue", on: true }
];
collection.reset(switches);
现在我的收藏中有3个型号。我希望他们拥有toggle()
方法:
toggle: function() {
this.save({ on: !this.get("on") })
}
如何添加?
答案 0 :(得分:1)
当您未将模型传递到骨干集合时,骨干网使用普通模型。如果您想拥有自定义模型,则应使用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();