robzolkos
7/23/2012 - 10:45 AM

Nested model in backbone.js

Nested model in backbone.js

Usage

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

TODO

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