Best practice for saving an entire collection?

后端 未结 4 1233
生来不讨喜
生来不讨喜 2020-12-08 06:55

Say that I have a Collection and I\'ve made changes to many of its Models. What\'s the best way to save all of the changes using a single HTTP request?

4条回答
  •  有刺的猬
    2020-12-08 07:45

    You should extend Backbone.Collection, giving it a save() method that would check each of its models hasChanged().

    Then it should call Backbone.sync, which you'll probably have to extend a little into a custom sync function. If you do use a custom Backbone.sync function, then be sure to set it on your collection.

    var CollectionSync = function(method, model, [options]) {
        // do similar things to Backbone.sync
    }
    
    var MyCollection = Backbone.Collection.extend({
        sync: CollectionSync,
        model: MyModel,
        getChanged: function() {
            // return a list of models that have changed by checking hasChanged()
        },
        save: function(attributes, options) {
            // do similar things as Model.save
        }
    });
    

    A different approach (using a model to represent the collection) is here: "How" to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?

    I also like https://stackoverflow.com/a/7986982/137067

提交回复
热议问题