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:
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?
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.
It’s probably because note.id is returning true.
The good news is Backbone already has a convention to set the model’s
idproperty to a specific attribute on the model. This is done by setting theidAttribute(See this line in Backbone’s source)With this code, Backbone will take care of setting
note.id = note.get('noteid')