I’m trying to find a way to change/update a model inside a collection without first explicitly initializing it.
The idea is that I’m createing a new collection instance by passing a hash of objects to it. I am assuming that Backbone automagically creates model instances for each object (am I right?).
Now, if this is true, I should somehow be able to change / update the model in the collection, shouldn’t I?
I have tried this, but it doesn’t work:
serie = view.collection.get(serie_id);
serie.set({
name: view.$('.series-name').val(),
format: view.$('.series-format').val(),
number: view.$('.series-number').val()
});
I don’t think you can just pass in any hash of objects and have Collection automagically create models. You need to instantiate models and pass them in as a models array.
I think what you’re talking about is something like this though:
When you specify the model attribute on the collection Class, then you can utilize the create() function of your collection and it will instantiate a model just by passing a hash of attributes.
If you set up your Serie model with some arbitrary default values, you could just run a loop and create a bunch of empty models. Then you could use the code you listed above to change those attributes using the .get(id) .set() methods. Although is there a good reason you want to do things this way?
It feels like using the .create() method as needed would work for most use cases.