Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically save after adding model to collection

Tags:

backbone.js

I have a collection myCollection to which I add models as follows:

myCollection.add({title: Romeo and Juliette, author: Shakespear});

Have can I now save this added model to the server? Backbone Collections do not have a save() and I do not a reference to the added model to call save directly.

like image 861
Randomblue Avatar asked Dec 23 '11 22:12

Randomblue


2 Answers

You can use the create function on the collection to add a model and have it automatically saved to the server.

myCollection.create({title: Romeo and Juliette, author: Shakespeare});

Here's the documentation on the create function.

like image 82
Paul Avatar answered Nov 09 '22 00:11

Paul


You could bind the save method of your collection to the add event:

MyCollection = Backbone.Collection.extend({
    initialize: function(){
        this.bind('add', this.save, this)
    }
    save: function(){
        $.post(this.url, this.toJSON())
    }
})
like image 30
Andreas Köberle Avatar answered Nov 08 '22 23:11

Andreas Köberle