Nested model in backbone.js
Initialise the collection in the constructor, defining the attribute and the collection to create
@initNestedCollections
accounts: Users.Collection.Accounts
Instead of calling @get('accounts') that will return the array, call @getNestedCollection('accounts') to get a collection
Add the collection to the output of toJSON (but that was not a requirement for me doing this)
Use the idea from meninges models to add new, update existing and remove missing models in the resetNestedCollections method
do ->
_parse = Backbone.Model.prototype.parse
_.extend Backbone.Model.prototype,
initNestedCollections: (nestedCollections) ->
@_nestedCollections = {}
_.each nestedCollections, (theClass, key) =>
@_nestedCollections[key] = new theClass([])
@resetNestedCollections()
parse: (response) ->
attributes = _parse(response)
@resetNestedCollections()
attributes
resetNestedCollections: () ->
_.each @_nestedCollections, (collection, key) =>
models = _.map @get(key), (attributes) =>
model= new collection.model()
model.set(model.parse(attributes))
collection.reset(models)
getNestedCollection: (name) ->
@_nestedCollections[name]
class MyApp.Model.User extends Backbone.Model
constructor: (attributes) ->
super(attributes)
@initNestedCollections
accounts: Users.Collection.Accounts