Backbone.js – Nested Collections and Arrays
I have recently been wrestling with Backbone.js to get it to correctly parse nested collections. There are numerous ways you can do this including using the plugin Backbone Relational. However, if you just want to do it yourself without the plugin then this is the approach that I found worked for me….
I have a collection of models. Some of these models might contain a nested collection of the same models. In my JSON this is set up as an array. The issue I was getting was that it was remaining as an array and not getting parsed into the collection of models I wanted it to be. This was a problem because I was navigating through the data recursively and I wanted to be able to treat each model as a Backbone model and not just a plain old object.
My model class is called ShellMenuModel and my collection class is called ShellMenuCollection. The model attribute where the nested collection would live is called subMods. Here is the model code:-
The key to solving this problem was using the initialize function to manually parse the collection. In this function we check to see if the subMods collection attribute exists, if it does exist then you instantiate a new collection and in the constructor pass in the subMods array. The collection then gets parsed into a collection and set up as the subMods attribute on the parent model.