Ember:如何从嵌套模型中获取计算属性?

时间:2015-06-19 16:10:21

标签: ember.js ember-cli rsvp-promise

首先:我不知道如何在Ember.js中使用promises。 我想调用我的控制器的属性,它取决于同步模型数据,它也是嵌套的。

另外,我的模型看起来像这样:

+-------------+         +------------+ 
| Method      | hasMany |  Practice  | 
|             +--------->            | 
|             |         |            | 
+-------------+         +------------+ 
                              |        
                              | hasMany
                        +-----v------+ 
                        | Alpha      | 
                        |            | 
                        |            | 
                        +------------+

所以我创造了这样的东西:

allAlphas: function() {

  var self = this;
  var returnValue = "nichts";

  var promises = {
    allAlphas: self.get('model.method').then(function(method) {
      //get the practices
      return method.get('practices');
    }).then(function(practices) {
      //get the alphaSField in EVERY practice
      //the alphasField is the (hasmany 'alpha')member in practice
      var alphasFields = practices.getEach('alphas');
      return Ember.RSVP.all(alphasFields).then(function() {
        return alphasFields;
      });

    }).then(function(alphasFields) {

      // here: get all the alphas via promise or something

    })
  };


  Ember.RSVP.hash(promises).then(function(results) {

    // return all the alphas (of all pracitces in the method) in some way 
  });


}.property()

有两个问题(如评论中已经提到的那样):

  1. 如何在所有实践中加载嵌套的hasMany异步模型,如所有alpha。
  2. 如何将完整结果作为RSVP.hash-Method中的属性返回,以便在模板或其他内容中使用
  3. 有人能帮助我吗?

    编辑06/20/2015

    正如@ Kingpin2k建议的那样,我添加了一个Gist,以便更好地理解我的问题: https://gist.github.com/MarcManhart/e5c1d91e8fdfd876de37

1 个答案:

答案 0 :(得分:2)

只返回一个数组,并在事后填充数组。

allAlphas: function() {
  var self = this,
      returnValue = [];

  this.get('model.method').then(function(method) {
    //get the practices
    return method.get('practices');
  }).then(function(practices) {
    //get the alphasField in EVERY practice
    //the alphasField is the (hasmany 'alpha')member in practice
    var alphas= practices.getEach('alphas');
    Ember.RSVP.all(alphas).then(function(resolvedAlphas) {
      resolvedAlphas.forEach(function(afs){
        returnValue.pushObjects(afs.toArray());
      });
    });
  });

  return returnValue;
}.property()

更新

看起来pushObjects并不喜欢ED收藏(或者它可能不喜欢下面的承诺,我没有那么多地研究它)。另外,我们应该使用已解决的值而不是我在下面的代码中发送的承诺(alphas vs resolvedAlphas。)

示例:http://emberjs.jsbin.com/cinobetoyu/1/edit?js,output