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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -