-1

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?

Mikhail Batcer
  • 1,938
  • 7
  • 37
  • 57

1 Answers1

1

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();
Ram
  • 143,282
  • 16
  • 168
  • 197
  • I've updated the question replacing arrow function with normal. The value of `this` is not the issue, the question is not about that. – Mikhail Batcer Jul 12 '16 at 13:03