【问题标题】:Backbone.js: Is there a way to set a property for all models in a collection when creating the collectionBackbone.js:有没有办法在创建集合时为集合中的所有模型设置属性
【发布时间】:2012-06-08 18:16:21
【问题描述】:

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

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

【问题讨论】:

    标签: javascript backbone.js


    【解决方案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;
    

    【讨论】:

    • 集合中的模型已经有一个.collection(参见jsfiddle.net/ambiguous/HxutA),但我认为这不是记录在案的行为(至少我粗略地找不到任何支持文档搜索)。
    • 亩,很酷。这可能就是我正在寻找的......我可以将 allSchools 设置为集合上的一个属性,然后模型可以通过 .collection.allSchools 访问它。把它写成答案并假设它有效,它是你的:)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2016-04-29
      • 1970-01-01
      相关资源
      最近更新 更多