EmberJs filterBy没有返回结果

时间:2014-08-01 16:21:06

标签: ember.js

我正在努力解决我所看到的问题并且调试变得困难。请参阅下面的代码段;

值得注意的是,这是一个稍微重构的版本,以使那些不了解我工作的域的开发人员更具可读性......

 // snippet function from my controller
 availableChildren: Em.computed(function () {
    var adult = this.get('selectedAdult');
    var isMale = this.get('showOnlyBoys');
    if (adult === undefined || adult === null)
        return [];

    var children = adult.get('children');
    console.log(children); // returns Class {isFullfilled: false ...}
    console.log(children.length); // returns undefined
    console.log(children.get('length')); // returns 0
    console.log(Ember.isArray(children)); // returns true
    var childArray = Ember.makeArray(children);
    console.log(childArray); // returns Class {isFullfilled: false ...}
    console.log(childArray.get('length')); // returns 0
    console.log(isMale); // returns true, half the children are male
    var boys = childArray.filterBy('isMale', isMale);
    console.log(boys); // returns [_super: function, nextObject ...]
    console.log(boys.length); // returns 0
    // when this is bound to the Ember.Select it is populated with all 
    // the children of the selected parent
    return children;
    // if I comment out the line above and return the boys then the 
    // Ember.Select is not populated with anything
    return boys;
}).property('selectedAdult', 'showOnlyBoys'),

App.Parent = DS.Model.extend({
   name: DS.attr('string'),
   isMale: DS.attr('bool'),
   children: DS.hasMany('child', { async: true })
});

App.Child = DS.Model.extend({
   name: DS.attr('string'),
   isMale: DS.attr('bool'),
   parent: DS.belongsTo('parent', { async: true })
});

// in my html
{{view Ember.Select
    content=availableChildren
    optionLabelPath="content.name"
    optionValuePath="content.id"
    selection=selectedChild
    prompt="Please Select..."
}}

正如您所看到的,我正在尝试根据填充selectedAdult变量的另一个下拉列表的结果来驱动下拉列表中的项目。如果我只返回所选父级的未过滤子项,则依赖下拉列表会按预期呈现,但是如果我尝试过滤结果,则下拉列表中没有任何内容。

我尝试了各种各样的方法,包括Ember.RSVP.filter,但我认为这是默默无效的,因为从adult.get(' children')派生的children变量不是一个承诺,它是一个Ember.Object。

我撞到墙上的那个位是Ember.isArray()返回true,但是当我试图获得长度时(为了调试目的),我总是得到零。然后思考过程,好吧,也许我必须投射到一个阵列,因为它目前是一个Ember.Object'但那也没有用。

任何人的想法?

1 个答案:

答案 0 :(得分:1)

console.log(children); // returns Class {isFullfilled: false ...}

这意味着您的承诺尚未解决,因此没有数据。 Ember-Data返回PromiseArray,这是一个promise,但实现了数组方法。因此,您可以像普通数组一样对待它,但只有在它被解决之后才能对待它。尝试将selectedAdult.children.@each添加到您的媒体资源的相关键。该属性仍将在promise解析之前计算,但它应该在promise结算时计算最后一次。

availableChildren: Em.computed(function () {
    var adult = this.get('selectedAdult');
    var isMale = this.get('showOnlyBoys');
    if (adult === undefined || adult === null)
        return [];

    var children = adult.get('children');
    return Ember.makeArray(children).filterBy('isMale', isMale).toArray();
}).property('selectedAdult.children.@each', 'showOnlyBoys'),
相关问题