javascript - Backbone collection: add logic to item models -
i update backbone collection array of bare objects using reset
:
const collection = new backbone.collection(); // ... const switches = [ { color: "red", on: false }, { color: "green", on: false }, { color: "blue", on: true } ]; collection.reset(switches);
now there 3 models in collection. want them have toggle()
method:
toggle: function() { this.save({ on: !this.get("on") }) }
how can add it?
when don't pass model backbone collection, backbone uses normal models. if want have customized models, should define model using backbone.model.extend()
function , pass collection:
const model = backbone.model.extend({ toggle: function() { this.save({ on: !this.get("on") }) } }); const collection = backbone.collection.extend({ model: model }); const collection = new collection();
Comments
Post a Comment