I am building an application which is built with Backbone.js. It contains several forms, which make it possible to create sub-items in collections. I run into the issue of getting the id for the recently created items. Let me explain the scenario:
- a new model instance is created with and an empty
id - the form gets saved triggering a POST or PUT request
- the server receives and saves the new and updated items
- the new items get the
idsfilled out - all items are sent back with updated server-side
ids
The issue is with mapping the new ids to the instances which are on the client side without an id.
Backbone.js generates a unique client-side cid for every object. The idea was to serialize the cid and send it back from the server with the server side id. As server I use rails. I added new virtual attribute cid to the model and serialized it. For the client models serializing (toJSON) and parsing needed to be updated. Method toJSON was the easy part:
1 2 3 4 | |
Bit trickier is handling of the response coming from the server. It’s necessary to identify the existing item using the cid and update it with the new server side id. After exploring several possible ways, how to do it wrong, I was advised to override the parse method.
1 2 3 4 5 6 7 8 | |
That simple definition of the parse method showed me the elegance of backbone. Searching for a simple solution proved to be worthwhile.


