3

I use Backbone with Marionette and backbone-relational.

Let's say I have a zoo with a Backbone.Collection of animals. I have one animal stored in the database (with the id 1). Now I add a second animal to the Backbone.Collection and call zoo.save({}, {wait: true}). In response my backend server returns both animals (the old one with id 1 and the new one with id 2). That works.

The problem: After saving the Backbone.Collection contains three models.

  1. an animal with id 1
  2. an animal without an id (just a cid)
  3. a new animal with id 2 as returned by the server

Instead I only want two models:

  1. an animal with id 1
  2. an animal with id 2

How can I tell Backbone to set the server id at the already existing animal instead of adding a new model to the collection?

Additional information:

My Zoo model extends Backbone.RelationalModel with relations defined as follows (similar to the example at http://backbonerelational.org/#RelationalModel-relations):

relations: [
    type:           Backbone.HasMany
    relatedModel:   'Animal'
    collectionType: 'AnimalCollection'
    key:            'animals'
]

That's why saving the zoo will update the collection as well.

Joshua
  • 63
  • 6

1 Answers1

0

I typically POST my new model via Ajax (since a model created on the clientside is not backed by any server data until it is created on the serverside), and in the success callback of my Ajax function add the model JSON returned from the server to the collection, thus making sure your data is driven by the backend, and you do not have hanging data/model on the clientside that would no longer exist on a reload.

Tyler Durden
  • 1,506
  • 13
  • 21