Skip to content

Instantly share code, notes, and snippets.

@rishabhmhjn
Created July 10, 2013 10:56
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 rishabhmhjn/5965374 to your computer and use it in GitHub Desktop.
Save rishabhmhjn/5965374 to your computer and use it in GitHub Desktop.
var ItemModel = Backbone.Model.extend({
defaults : {
"item_id" : 0,
"item_content" : "this is a content"
}
});
var ItemColl = Backbone.Collection.extend({
model : ItemModel
});
var ItemParentModel = ItemModel.extend({
initialize : function () {
this.set("childCollection", new ItemColl());
}
});
var ItemParentColl = ItemColl.extend({
model : ItemParentModel,
toJSON : function (options) {
return this.map(function (model) {
var data = model.toJSON(options);
data.childItems = data.childCollection.toJSON();
delete data.childCollection;
return data;
});
}
});
// ――――――――――――――――――――
var mainItems = new ItemParentColl();
mainItems.add({
item_id : 2121,
item_content : "Item 1"
});
mainItems.at(0).get('childCollection').add({
item_id : 2122,
item_content : "Item 2",
item_parent : 2121
});
mainItems.add({
item_id : 2123,
item_content : "Item 3"
});
mainItems.at(0).get('childCollection').toJSON();
// this has values
mainItems.at(1).get('childCollection').toJSON();
// this is empty
mainItems.toJSON();
// this shows the childItems as JSON items
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment