I see there are techniques available to have deep models in Backbone, but how about hierachical collections of a single model?
An obvious example is a category tree. So, we can have a category model which has a few properties, ‘name’, ‘type’, ‘color’, whatever.
Rather than have relational db style parent ids, we’re using js so we want the data to be represented as json.
Can backbone be leveraged to support (presumably by augmenting collections) data structures that contain instances of a single model in a tree (such that the models and sub models are all instances of the same model)?
Have a look at Backbone-Relational or supermodel.js.
These projects provide better forms of model nesting than the default implementation.
We just nest Backbone models like:
And we override the
toJSONmethods:So the JSON representations look correct when we nest models. You’ll have to pay attention to the
parsemethod on your model though – when you get back your JSON from the server you’re going to have to generate all the submodels and collections there in order for it all to work correctly.