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?
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