Javascript Backbone.js:在创建集合时,是否有方法为集合中的所有模型设置属性

Javascript Backbone.js:在创建集合时,是否有方法为集合中的所有模型设置属性,javascript,backbone.js,Javascript,Backbone.js,我想知道在实例化一个新集合时,是否有任何方法可以传递一个值,该集合将被设置为添加到集合中的所有新模型的属性。例如: allSchools = [/* list of schools */]; this.schoolTypes = new Backbone.Collection([], { model:SchoolType }); //pass in allSchools here, somehow this.schoolTypes.add({name:'New SchoolType'}); 其

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

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对象,但它不是很模块化。

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

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;

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

schoolType = schoolTypes.at(0);
allSchools = schoolType.collection.allSchools;

集合中的模型已经有了一个
.collection
(请参阅),但我认为这不是有文档记录的行为(至少我无法通过粗略搜索找到任何支持文档)。穆,很酷。这可能就是我要找的。。。我可以将allSchools设置为集合的属性,然后模型可以通过.collection.allSchools访问它。把它写下来作为一个答案,假设它有效,它就是你的:)