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 id
property to a specific attribute on the model. This is done by setting the idAttribute
(See this line in Backbone's source)
var Note = Backbone.Model.extend({
idAttribute: 'noteid'
});
With this code, Backbone will take care of setting note.id = note.get('noteid')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.