Suppose I have a Backbone.Collection
with three models. I want to replace the middle one, keeping the first and third models in their current positions. (Assume there's no comparator
.) How do I do this?
write("<br>"); //The remove() method removes the 'player1' model from the collection. mycollection.
js respectively. The rest of your application code should be divided into modules that can live under their own modules directory. A module is an encapsulated group of structures (for the purposes of our post, Backbone structures) that work cohesively to provide a subset of functionality in your application.
Model. Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.
This is a good question and still relevant today, so it's worth answering.
It is possible the functionality used in my answer did not exist when you asked the question, but it is now quite straightforward to do this.
Anyway, lets assume your collection is named myCollection
and already has 3 models stored in it. Lets also say you have a new model named newModel
that you want use to replace the existing middle model in the collection. To replace the middle model, leaving the first and third models untouched, you can do this:
myCollection.remove(myCollection.at(1));
myCollection.add(newModel, {at: 1});
This will do exactly what you want and raise the remove
event for the model removed and the add
event for the replacement, which is what you wanted also.
There is a simple mechanism built into Backbone that handles this issue
myCollection.add(newModel, {merge: true});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With