0

我想知道当我实例化一个新集合时是否有任何方法可以传入一个值,该集合将被设置为添加到集合中的所有新模型的属性。例如,

allSchools = [/* list of schools */];
this.schoolTypes = new Backbone.Collection([], { model:SchoolType }); //pass in allSchools here, somehow
this.schoolTypes.add({name:'New SchoolType'});

新添加的模型将有一个 this.allSchools (或 this.options.allSchools 或类似的东西)。似乎应该有一个足够简单的方法来做到这一点?目前我只是访问一个全局 allSchools 对象,但它不是很模块化。

4

2 回答 2

1

这可能不是最好的方法,但您可以向模型添加一个反向链接,让它访问它的父集合:

this.schoolType.allSchools = allSchools;
var col = this.schoolType;
this.schoolType.each(function(el,i){
    el.collection = col;
});
// ...
// then access all the schools from your SchoolType model `m` : 
if(m.collection)
    var allSchools = m.collection.allSchools;
于 2012-06-08T18:26:07.077 回答
0

正如 mu 在他的评论中提到的,模型具有内置的 .collection 属性。所以,如果我在集合上设置一个属性,我可以从集合中的任何模型访问它,如下所示:

schoolType = schoolTypes.at(0);
allSchools = schoolType.collection.allSchools;
于 2012-06-16T15:30:54.147 回答