3

We're saving a collection of a model but backbone seems to want to do these one after the other. This can be expensive and takes a while to complete which can lead to data not being saved if the user refreshes or navigates away from the page mid process.

Is there a way to get Backbone to send them off as an array?

How would I do this?

code that does the saving:

_(this.models).each(

            function(guest) {

                if (tid == guest.get('tableId') || guest.get('tableId') == null) {
                    guest.set({ tableId: tid });
                    guest.save();
                }
            }
);

1 Answers1

2

I've been thinking about this for a while... REST doesn't define a push of multiple items (that I am aware of) so you will have to write some custom stuff to make it happen.

I think the best way to go is to create a custom route on the back-end that is is a PUT to your /entities path, much like the existing GET which is really just an "index". It would take a JSON collection much like the GET returns a JSON collection now.

Then, you would need to override Backbone.Collection to include a save function. Since Backbone.sync only has the four verbs (create, update, delete, read), you would want to do an "update" but you will probably have to write a bit of code so serialize your collection to a JSON collection and put it in the body. I'd expect a bit of overriding in Backbone.sync or just a custom call to $.ajax in your new Backbone.Collection.save function.

At least, that is how I'd attack it. :)

Brian Genisio
  • 47,787
  • 16
  • 124
  • 167
  • 1
    I agree, that's the way to do it. And you can use Backbone.sync, it works out of the box, see this code: http://stackoverflow.com/questions/7975316/how-to-save-a-collection-with-backbone-js/7986982#7986982 – dira Nov 03 '11 at 15:30
  • dira got it right but i'll mark this q right as there's no other way to do it :s –  Nov 03 '11 at 16:16