Today I updated backbone.js (0.9.2 => 0.9.9) and backbone-relational (0.5.0 => 0.7.0), and a piece of code stopped working and I can't figure our why. (I even tried to upgrade step by step (e.g. backbone-relational 0.5.0 => 0.6.0), but that didn't helped.)
My models (a book that contains several chapters):
window.Book = Backbone.RelationalModel.extend({
relations:[{
type: Backbone.HasMany,
key:"chapters",
relatedModel: "Chapter",
collectionType:"ChaptersCollection",
reverseRelation:{
key:"book"
}
}]
});
window.BookCollection = Backbone.Collection.extend({
model: Book,
url: "/books"
});
window.Chapter = Backbone.RelationalModel.extend();
window.ChaptersCollection = Backbone.Collection.extend({
model: Chapter,
url: "/chapters"
});
Now I want to add a chapter to an existing book, and do something during the "add" event. The problem is that chapter.get("book")
is undefined
, although the book is returned in the success
callback. But see yourself:
var book = ...;
book.get("chapters").on("add", function (chapter) {
console.log("add");
console.log(chapter.get("id"));
console.log(chapter.get("book_id"));
console.log(chapter.get("book"));
});
var chapter = book.get("chapters").create({title:"Foo"}, {
wait: true,
success:function () {
console.log("success")
console.log(chapter.get("id"));
console.log(chapter.get("book_id"));
console.log(chapter.get("book"));
}
});
Console output:
> add
> 83
> 3
> null <<<<<<< Expecting a book object here, why null?
> success
> 83
> 3
> Book{...}
Do you have any idea what I am doing wrong?