Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

5/26/2013

How to save Backbone collection to the server ?


Backbone Collection doesn't have save method, it is only avaliable on the Model instances. So how can we save collections to the server ?

There are couple of workarounds. I found  one very elegant solution, which wraps model around collection. It is opposite to common pattern in which collection is a wrapper around models.

Here is a basic skeleton of this idea:

//
// collection class extended
var CDShop = Backbone.Collection.extend();

// collection instance 
var CDShopInstance = new CDShop([
    {
        title: "Blue Train",
        author: "John Coltrane"
    },
    {
        title: "Intercontinental",
        author: "Joe Pass"
    },
    {
        title: "Confirmation",
        author: "Charlie Parker"
    }

]);

// model class extended
var MusicShop = Backbone.Model.extend({
    defaults: {
        title: "",
        author: ""
    },
    // passing collection as a property of instance
    model: CDShopInstance,
    // imaginary url 
    urlRoot: "/shop"
});
// model instance 
var musicShopInstance = new MusicShop;

// testing returns three objects from the collection
console.log(musicShopInstance.model.toJSON());

// now we can save out collection to the server  
musicShopInstance.save();
//

Happy Coding.

No comments:

Post a Comment