骨干关系:保存期间关系丢失

时间:2013-01-11 14:23:56

标签: backbone.js backbone-relational backbone-collections

今天我更新了backbone.js(0.9.2 => 0.9.9)和骨干关系(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{...}

你知道我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

问题似乎是当为子集合触发add事件时,反向关系尚未更新。我不确定Backbone或Backbone之间的哪些变化。版本之间的关系导致了这种变化,但它很容易修复。

而不是像在此处那样收听相关集合上的add事件:

book.get("chapters").on("add", function (chapter) {

您应该按照Backbone.Relational documentation中所述,听取模型本身的add:<key>事件:

book.on("add:chapters", function (chapter) {

查看this fiddle了解工作示例。