【问题标题】:Create a collection from inside a collection从集合内部创建集合
【发布时间】:2014-01-10 00:35:23
【问题描述】:

我有一个集合,它在获取时会得到一个 json 并放入集合中: JSON格式为:

[ 
  {
    name: 'Hello',
    age: '22',
    bio: [{
      interest: 'soccer',
      music: 'r&B'
    }]
  }
]

我想从 bio 制作另一个集合(无需再次获取)。 原因是我想同时访问姓名、年龄和简历,而解析函数只能返回一个?

var user = new Backbone.Collection.extend({
  url: '/user',

  parse: function (response) {
    //I want both of this?
    //return response;
    return response.bio;
  }
});

我将这个关于 fetch 成功函数的集合传递到两个不同的视图中。

//Controller File....
.............

mycollection.fetch({
  success: function() {

    //Details View wants response
    PrimaryLayout.main.show(new detailsView{collection: mycoll});      

   //Bio View wants response.bio
    PrimaryLayout.body.show(new bioView{collection: mycoll}); 
  }
})

解决这个问题的最佳方法是什么?我可以克隆一个集合并在其中包含个人简介吗?

【问题讨论】:

    标签: json backbone.js marionette


    【解决方案1】:

    我通常通过在parse 中实例化子集合来解决这个问题:

    var User = Backbone.Model.extend({
        parse: function(json) {
            // instantiate the collection
            json.bio = new Backbone.Collection(json.bio);
            // now person.get('bio') will return a Collection object
            return json;
        }
    });
    
    var Users = Backbone.Collection.extend({
        model: User,
        // ...
    });
    

    【讨论】:

      【解决方案2】:

      我认为这就是您要寻找的内容:Backbone Associations。看看那里的教程和示例。

      【讨论】:

        猜你喜欢
        • 2020-07-03
        • 2014-10-11
        • 1970-01-01
        • 2018-09-20
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 2012-10-03
        • 2020-04-23
        相关资源
        最近更新 更多