Skip to content

Instantly share code, notes, and snippets.

@jrsalunga
Created September 23, 2013 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrsalunga/6665608 to your computer and use it in GitHub Desktop.
Save jrsalunga/6665608 to your computer and use it in GitHub Desktop.
Collection inside Model
var Document = Backbone.Model.extend({
constructor: function() {
this.items = new ItemSet(null, {document: this});
this.items.on('change', this.save, this);
Backbone.Model.apply(this, arguments);
},
parse: function(resp) {
this.items.set(resp.items, {parse: true, remove: false});
delete resp.items;
return resp;
},
toJSON: function() {
var attrs = _.clone(this.attributes);
attrs.items = this.items.toJSON();
return attrs;
}
});
var ItemSet = Backbone.Collection.extend({
model: Item,
initialize: function(models, options) {
this.document = options.document;
}
});
var Item = Backbone.Model.extend({
// access document with this.collection.document
});
var document1 = new Document({
name: "Test",
version: 1,
items: [
{name : "Item 1", position : 0},
{name : "Item 2", position : 1}
]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment