Created
July 10, 2013 10:56
-
-
Save rishabhmhjn/5965374 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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