Automatically save after adding model to collectio

2019-04-18 23:42发布

问题:

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.

回答1:

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.



回答2:

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())
    }
})


标签: backbone.js