0

I have no problem saving a model one at a time, I wrote a recursive save on an array of objects. on each successful save, i shift out an object and if the array length is not 0 -> repeat... once the array length reaches zero then I know all saves were successful and do the appropiate action.

wondering outloud if there is a better way? than the approach described above the rest service api doesn't take a collection but if I had an example of saving a collection, I'd ask for the service to be modified.

jsdev
  • 1
  • 1
  • Looks like a duplicate of http://stackoverflow.com/questions/6879138/how-to-save-an-entire-collection-in-backbone-js-backbone-sync-or-jquery-ajax. – Lukas Jan 03 '13 at 19:40

2 Answers2

6

Although there is no save method built in to a Collection, this can certainly be a good idea. Your situation sounds like it would benefit form this, as looping through each model and saving them individually is a really really really expensive network traffic way of getting this done.

At it's core, Backbone uses jQuery's AJAX to post to the server... so why not take advantage of that with your collection?


$.ajax({
  type: "POST",
  url: "/my/api",
  dataType: "JSON",
  data: myCollection.toJSON()
});

This will post an array of objects as JSON back to the server at the /my/api endpoint. You could easily wrap this up in to a method on your collection or in another object.

Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
  • 4
    With Backbone 0.9.9, `myCollection.sync('update', myCollection)` will send a PUT request with the array of objects. – nikoshr Jan 02 '13 at 13:21
1

i do it with a save function direct in collection:

Backbone.sync('update', this, {
    success: function() {
        alert('saved');
    }
});

Hope it helps.

Moszeed
  • 1,037
  • 1
  • 10
  • 20