“How” to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?

前端 未结 11 1306
醉梦人生
醉梦人生 2020-11-28 19:45

I am well aware it can be done and I\'ve looked at quite a few places (including: Best practice for saving an entire collection?). But I\'m still not clear \"exactly how\"

11条回答
  •  感动是毒
    2020-11-28 20:20

    The answer depends on what you want to do with the collection on server side.

    If you have to send additional data with the post you might need a wrapper model or a relational model.

    With the wrapper model you always have to write your own parse method:

    var Occupants = Backbone.Collection.extend({
        model: Person
    });
    
    var House = Backbone.Model.extend({
        url: function (){
            return "/house/"+this.id;
        },
        parse: function(response){
            response.occupants = new Occupants(response.occupants)
            return response;
        }
    });
    

    Relational models are better I think, because you can configure them easier and you can regulate with the includeInJSON option which attributes to put into the json you send to your rest service.

    var House = Backbone.RelationalModel.extend({
        url: function (){
            return "/house/"+this.id;
        },
        relations: [
            {
                type: Backbone.HasMany,
                key: 'occupants',
                relatedModel: Person,
                includeInJSON: ["id"],
                reverseRelation: {
                    key: 'livesIn'
                }
            }
        ]
    });
    

    If you don't send additional data, you can sync the collection itself. You have to add a save method to your collection (or the collection prototype) in that case:

    var Occupants = Backbone.Collection.extend({
        url: "/concrete-house/occupants",
        model: Person,
        save: function (options) {
            this.sync("update", this, options);
        }
    });
    

提交回复
热议问题