Skip to content

Instantly share code, notes, and snippets.

@dougo-chris
Created March 22, 2012 12:01
Show Gist options
  • Save dougo-chris/2157924 to your computer and use it in GitHub Desktop.
Save dougo-chris/2157924 to your computer and use it in GitHub Desktop.
Nested model in backbone.js
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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment