[英]Binding to add on a backbone.js collection
I'd like to set a model's ID to the correct value after a fetch in all instances of a backbone collection, but this doesn't seem to work: 我想在一个骨干集合的所有实例中获取后,将模型的ID设置为正确的值,但这似乎不起作用:
var NoteCollection = Backbone.Collection.extend(
{
model: Note,
initialize: function () {
this.bind("add", function (note) {
if (!note.id && note.has('noteid'))
note.id = note.get('noteid');
});
}
});
The function never gets called (I'm testing by creating a new NoteCollection and calling fetch on it), what am I doing wrong? 函数永远不会被调用(我正在通过创建一个新的NoteCollection并在其上调用fetch来测试),我做错了什么?
Note: I know I could bind the method on a specific instance of NoteCollection, and that works, but I want to bind it on all instances. 注意:我知道我可以在NoteCollection的特定实例上绑定该方法,这是有效的,但我想在所有实例上绑定它。
It's probably because note.id is returning true. 这可能是因为note.id返回true。
The good news is Backbone already has a convention to set the model's id
property to a specific attribute on the model. 好消息是Backbone已经有了一个约定,可以将模型的
id
属性设置为模型上的特定属性。 This is done by setting the idAttribute
(See this line in Backbone's source) 这是通过设置
idAttribute
来完成的(在Backbone的源代码中查看此行 )
var Note = Backbone.Model.extend({
idAttribute: 'noteid'
});
With this code, Backbone will take care of setting note.id = note.get('noteid')
使用此代码,Backbone将负责设置
note.id = note.get('noteid')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.