Search code examples
javascriptbackbone.jsbackbone.js-collections

How to update the whole Backbone.js collection that in database?


I have a collection (an object list) in database. I can fetch it like: collectionModel.fetch() But then user changes something on that collection. When user clickes on save button, the whole collection list must be update in database. I thought maybe i can delete() the old one first and then create() it with new one but i could'n achive it. I can't use the update() method because in this case i should find which collection elements has changed but i want to update whole list. How can i do that? Thanks for help.


Solution

  • Do you have a REST api in front of that database? That's how Backbone is made to work with. When your JavaScript code runs model.save(); a PUT request is made to your api for that model.

    You question is about saving the whole collection, for that if you want to remain within the default implementation of Backbone you will have to go over all the models in the collection and call save for each of them.

    If you want to make one single request to your server you will have to implement a custom method inside your collection. Something like:

    MyCollection = Backbone.Collection.extend({
        saveAll: function() {
            var data = this.toJSON();
            return Backbone.$.ajax({
                data: { objects: data },
                url: '/url/in/your/server/to/update/db'
            });
        }
    });
    

    That's going to send the array of all models in your collection converted to JSON to your server.

    Again, you want to have a RESTful API on the server side if you want to make your life with Backbone easy.