Automatically save after adding model to collectio

2019-04-18 23:19发布

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.

标签: backbone.js
2条回答
我想做一个坏孩纸
2楼-- · 2019-04-18 23:56

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-04-18 23:57

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())
    }
})
查看更多
登录 后发表回答