Search code examples
javascriptbackbone.jsbackbone.js-collections

Backbone collection: add logic to item models


I update a Backbone collection from array of bare objects by 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 are 3 models in my collection. I want them to have toggle() method:

toggle: function() { 
    this.save({ on: !this.get("on") }) 
}

How can I add it?


Solution

  • When you don't pass a model to a backbone collection, backbone uses normal models. If you want to have a customized models, you should define a model by using the Backbone.Model.extend() function and pass it to the 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();