When mapping a Backbone Model directly to a REST API it is common for the resource you’re accessing to have a nested or associated resources. Backbone Models are a wrapper for a single resource, but do not attempt to implement a nested resource relationship. Backbone Collections also provide a nice mechanism to @fetch@ multiple resources at a time but also do not work well for a nested resource structure.
In our application we have a @Question@ model that has many @Answers@. When using a collection to fetch our questions we also want, in the same call, to fetch the answers. This is what we’ve tried so far.
Our first attempt was using the Collection#parse function provided by Backbone. This method, however, is only for updating the raw attributes and returning model attributes. Hooking into the creation of the model needs to take place somewhere else.
For our second attempt, we tried binding to change events on the model during @initialize@. This also did not work. The attributes on the model were already populated by the time @initialize@ happens, so change events were not fired on creation.
In our third attempt we used a collection to fetch the models and their nested associated resources. We bound to the @reset@ call on the collection and then iterated over each of our models, instructing them to build out their associated models based on their attributes.
This provided us with a partial solution. We were able to get a model nested inside of another model. Unfortunately, when trying to save back out to the server Backbone had no idea what to do with the nested model. We solved this temporarily by overriding our @toJSON@ method.
At some point soon we hope to try the Backbone Relational library, which seems to solve nested relationships in Backbone. It should allow us to move away from the temporary @toJSON@.