I have a single page application using backbone to manage a collection of models.
Sometimes this collection gets quite large and if the user performs operations that change a lot of them this can result in .save getting called lots of times. In some cases resulting in hundreds of ajax requests firing simultaneously.
Does backbone provide any way to batch operations like these into a single request? Or is there a preferred pattern to use?
Thanks for any advice.
There is no built-in way to batch operations for a Backbone.Collection. A common pattern to use is to wrap the collection in a Backbone.Model and simply overwrite the toJSON
method. You can then treat this like any other Backbone.Model and simply call save()
.
var Post = Backbone.Model.extend({
...
});
var Posts = Backbone.Collection.extend({
model: Post,
...
});
var PostsList = Backbone.Model.extend({
url: '/path/for/bulk/operations',
toJSON: function() {
// the model in this case is the Posts collection
return this.model.toJSON();
}
});
Another option is to simply add a save()
method to your collection and delegate to Backbone.Sync
var Posts = Backbone.Collection.extend({
...
save: function( options ) {
return Backbone.sync( 'create', this, options );
}
});