Backbone nested collection

后端 未结 1 892
萌比男神i
萌比男神i 2021-02-02 01:46

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

1条回答
  •  臣服心动
    2021-02-02 02:03

    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'});
    

    0 讨论(0)
提交回复
热议问题