Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a model in a Backbone.Collection?

Tags:

backbone.js

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?

like image 551
Trevor Burnham Avatar asked Jun 06 '11 18:06

Trevor Burnham


People also ask

How do I remove a model from a collection backbone?

write("<br>"); //The remove() method removes the 'player1' model from the collection. mycollection.

What is module in Backbone JS?

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.

What is a model backbone?

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.


2 Answers

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.

like image 136
dcarson Avatar answered Sep 19 '22 12:09

dcarson


There is a simple mechanism built into Backbone that handles this issue

myCollection.add(newModel, {merge: true});

like image 22
John Clarke Mills Avatar answered Sep 21 '22 12:09

John Clarke Mills