如何合并Emberjs中的嵌套模型收集



考虑此模型:

Grandparent
  parents: DS.hasMany('parent')
Parent:
  grandparent: DS.belongsTo('grandparent')
  children: DS.hasMany('child')
Child:
  parent: DS.belongsTo('parent')

我想将计算的属性children添加到Grandparent型号中,我期望Child型号的集合(祖父母.children =合并每个祖父母.parents.parents.children)。

如何做?

对于此示例数据:

Grandparent { id: 0, parents: [0, 1] }
Parent { id: 0, grandparent: 0, children: [0] }
Parent { id: 1, grandparent: 0, children: [1,2] }
Child { id: 0, parent: 0 }
Child { id: 1, parent: 1 }
Child { id: 2, parent: 1 }

我希望Grandparent.get('children')返回具有IDS [0,1,2]的孩子。

编辑:

App.Grandparent.reopen({
  grandchildren: function(){
    var result = [];
    this.get('parents').forEach(function(parent) {
      parent.get('children').forEach(function(child){
        console.log('is this even called?');
        result.push(child);
      });
      console.log('coz this is!');
    });
    return result;
  }.property("parents", "parents.@each.children")
});

为什么第二个环为空?我知道数据已加载(Ember Inspector)。

edit2:

几乎在那里!看来清单是空的,因为这是一个承诺数组(尚未解决),因此在执行代码时 - 它是空的!

 grandchildren: function(){
    var grandchildren = [];
    this.get('parents').forEach(function(parent) {
      var promiseArray = parent.get('children');
      promiseArray.then(function() {
        promiseArray.forEach(function(child){
          grandchildren.push(child);
          console.log(child);
        });
      });
    });
    return grandchildren;
  }.property("parents", "parents.@each.children")

因此,此代码在控制台中正确显示所有孙子...但是!它仍然不会返回它们。这可能是出于同样的原因 - 当代码击中return grandparent时,它仍然是空的。我现在在想,有办法解决吗?

edit3:

似乎问题的根源是DS.hasMany('parent', { async: true })DS.hasMany('child', { async: true })。我已经在原始问题中使用了异步部分,以使模型示例更加清晰。

edit4:

我通过从ds.hasmany中删除async: true解决了问题,并使用此脚本在没有异步的情况下正确加载它们。

这解决了"空数组"(未解决的承诺数组)的问题,并允许我访问属性。然后,我执行了以下代码(在模型的重新打开函数中):

grandchildren: function(){
  var res = Ember.ArrayProxy.create({content: Ember.A()});
  this.get('parents').forEach(function(parent){
    res.pushObjects(parent.get('children').toArray());
  });
  return res;
}.property('parents', 'parents.@each.children')

它有效!是的!

但是,我仍然对异步数据的解决方案感兴趣

下一步是用从服务器获取的一些数据替换固定装置。该数据是异步的。因此,我仍然需要一个带有承诺的解决方案。

edit5:测试代码:

grandchildren: function(){
  var res = Ember.ArrayProxy.create({content: Ember.A()});
  this.get('parents').forEach(function(parent) {
      var promiseArray = parent.get('children');
      promiseArray.then(function() {
        res.pushObjects(promiseArray.toArray());
      });
    });
  return res;
}.property('parents', 'parents.@each.children')

您可能正在寻找http://emberjs.com/api/classes/rsvp.html#method_all。

var promises = [];
this.get('parents').forEach(function(parent) {
  promises.push(parent.get('children'));
});
return Ember.RSVP.all(promises).then(function(results) {
  // return concatenated results
});

当您致电孙子时,您将得到一个解决串联结果的承诺。

将来看起来会通过类似的铁路对Hasmany提供支持。https://github.com/emberjs/data/issues/120

最新更新