Javascript Backbone:从集合视图向集合添加模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11438403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone: Adding a model to a collection from a collection view?
提问by theeggman85
I have some code where I want a NoteCollectionView to add a new Note to the NoteCollection. This is triggered by a function newNote in the NoteCollectionView:
我有一些代码,我希望 NoteCollectionView 向 NoteCollection 添加新的 Note。这是由 NoteCollectionView 中的函数 newNote 触发的:
newNote: function(data) {
var note = new Note(data);
this.collection.add(note);
},
I'm still very new to backbone, and I want to make sure this syncs with the server. The concerns I have are:
我对主干还是很陌生,我想确保这与服务器同步。我的顾虑是:
1) Will simply adding this note to the collection trigger a save() from the server, and update the model with the ID that the server gives it? Or,
1) 简单地将此注释添加到集合中是否会触发来自服务器的 save(),并使用服务器提供的 ID 更新模型?或者,
2) If the server does not update my model and give me an actual ID, how do I save the model with note.save() and get back an ID from the server?
2) 如果服务器没有更新我的模型并给我一个实际的 ID,我如何使用 note.save() 保存模型并从服务器取回一个 ID?
回答by Hymanwanders
To address your first question, no, .add
will not trigger any kind of call to the server; it will only add a model to a collection.
要解决您的第一个问题,不,.add
不会触发对服务器的任何类型的调用;它只会将模型添加到集合中。
However, you do have a couple options. One would be to create the new note model, save it to the database, and then add it to the collection:
但是,您确实有几个选择。一种是创建新的笔记模型,将其保存到数据库中,然后将其添加到集合中:
newNote: function(data) {
var note = new Note(data);
note.save();
this.collection.add(note);
}
The second option is to simply use Backbone's collection.create method. Give it a hash of attributes and it will
第二种选择是简单地使用Backbone 的 collection.create 方法。给它一个属性的散列,它会
- Create the model
- Save it to the database
- Add it to the collection
- 创建模型
- 将其保存到数据库
- 将其添加到集合中
All in one fell swoop, like so:
一举成名,就像这样:
newNote: function(data) {
return this.collection.create(data);
}
collection.create
also returns the newly created model, illustrated by my return statement above.
collection.create
还返回新创建的模型,如我上面的 return 语句所示。