I have an app in backbone that retrieve data from a server. This data are hotels and foreach hotel I have more rooms. I have divided hotel into a json and rooms inside another j
Here is how you can structure the Collections:
HotelModel = Backbone.Model.extend({
initialize: function() {
// because initialize is called after parse
_.defaults(this, {
rooms: new RoomCollection
});
},
parse: function(response) {
if (_.has(response, "rooms")) {
this.rooms = new RoomCollection(response.rooms, {
parse: true
});
delete response.rooms;
}
return response;
},
toJSON: function() {
var json = _.clone(this.attributes);
json.rooms = this.rooms.toJSON();
return json;
}
});
RoomModel = Backbone.Model.extend({
});
HotelCollection = Backbone.Collection.extend({
model: HotelModel
});
RoomCollection = Backbone.Collection.extend({
model: RoomModel
});
Then you can do something like this:
var hotels = new HotelCollection();
hotels.reset([{
id: 1,
name: 'Hotel California',
rooms: [{
id: 1,
name: 'Super Deluxe'
}]
}], {
parse: true // tell the collection to parse the data
});
// retrieve a room from a hotel
hotels.get(1).rooms.get(1);
// add a room to the hotel
hotels.get(1).rooms.add({id:2, name:'Another Room'});