从集合中引用模型

时间:2014-11-17 09:31:03

标签: javascript backbone.js backbone-collections backbone-model

我正在使用Backbone来构建我的Web应用程序,这是我的情况:

Section = Backbone.Model.extend({
     initialize: function(){
          this.set("elements", new ElementCollection());
     }
})

ElementCollection = Backbone.Model.extend({

     model: ElementModel

})

这种关系的含义是Section包含多个Elements。 我现在的目标是从ElementCollection引用其父Section模型。

我怎样才能做到这一点?

我尝试在setproperty Collection,例如:

this.set("parentSection", theParentSection")

但是这不起作用,实际上Collection中的标准set方法在其中添加了一个模型,这会破坏我的所有结构。

1 个答案:

答案 0 :(得分:1)

初始化时,您可以将父模型传递给集合:

Section = Backbone.Model.extend({
     initialize: function(){
          this.set("elements", new ElementCollection([], {parentModel: this}));
     }
})

ElementCollection = Backbone.Collection.extend({
     initialize: function (options) {
         this.parentSection = options.parentModel;
     }, 
     model: ElementModel
})