"How" to save an entire collection in Backbone.js - Backbone.sync or jQuery.ajax?

PhD picture PhD · Jul 29, 2011 · Viewed 47.2k times · Source

I am well aware it can be done and I've looked at quite a few places (including: Best practice for saving an entire collection?). But I'm still not clear "exactly how" is it written in code? (the post explains it in English. It'd be great to have a javascript specific explanation :)

Say I have a collection of models - the models themselves may have nested collections. I have overridden the toJSON() method of the parent collection and I am getting a valid JSON object. I wish to "save" the entire collection (corresponding JSON), but backbone doesn't seem to come in-built with that functionality.

var MyCollection = Backbone.Collection.extend({
model:MyModel,

//something to save?
save: function() {
   //what to write here?
 }

});

I know somewhere you have to say:

Backbone.sync = function(method, model, options){
/*
 * What goes in here?? If at all anything needs to be done?
 * Where to declare this in the program? And how is it called?
 */
}

Once the 'view' is done with the processing it is responsible for telling the collection to "save" itself on the server (capable of handling a bulk update/create request).

Questions that arise:

  1. How/what to write in code to "wire it all together"?
  2. What is the 'right' location of the callbacks and how to specify a "success/error" callback? I mean syntactically?I'm not clear of the syntax of registering callbacks in backbone...

If it is indeed a tricky job then can we call jQuery.ajax within a view and pass the this.successMethod or this.errorMethod as success/error callbacks?? Will it work?

I need to get in sync with backbone's way of thinking - I know I'm definitely missing something w.r.t., syncing of entire collections.

Answer

bradgonesurfing picture bradgonesurfing · Jul 30, 2011

My immediate thought is not to override the method on save method on Backbone.Collection but wrap the collection in another Backbone.Model and override the toJSON method on that. Then Backbone.js will treat the model as a single resource and you don't have to hack the way backone thinks too much.

Note that Backbone.Collection has a toJSON method so most of your work is done for you. You just have to proxy the toJSON method of your wrapper Backbone.Model to the Backbone.collection.

var MyCollectionWrapper = Backbone.Model.extend({
url: "/bulkupload",

//something to save?
toJSON: function() {
    return this.model.toJSON(); // where model is the collection class YOU defined above
 }

});