今天我更新了backbone.js (0.9.2 => 0.9.9) 和backbone-relational (0.5.0 => 0.7.0),一段代码停止工作,我不知道为什么。(我什至尝试逐步升级(例如骨干关系 0.5.0 => 0.6.0),但这并没有帮助。)
我的模型(包含几章的书):
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"
});
现在我想在现有书籍中添加一章,并在“添加”事件期间做一些事情。问题是chapter.get("book")
,undefined
虽然这本书是在success
回调中返回的。但是看看你自己:
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"));
}
});
控制台输出:
> add
> 83
> 3
> null <<<<<<< Expecting a book object here, why null?
> success
> 83
> 3
> Book{...}
你知道我做错了什么吗?