如何根据异步关系在Ember Data模型上执行Ember.js计算属性?

Ker*_*ick 3 ember.js ember-data

我有一个Ember Data模型,我正在尝试根据async hasMany关系的属性执行计算属性.出于某种原因,它似乎永远不会重新计算.我该怎么做呢?

代码:

export default DS.Model.extend({
    splits: DS.hasMany('split', { async: true }),
    amount: Ember.reduceComputed('splits.@each.amount', {
        initialValue: 0,
        addedItem: function(accValue, split) { return accValue + split.get('amount'); },
        removedItem: function(accValue, split) { return accValue - split.get('amount'); }
    })
    /* Neither of these work either.
    amount: Ember.computed.sum('splits.@each.amount') // This doesn't work
    amount: Ember.computed('splits.@each.amount', function() {
        return this.get('splits').reduce(function(pValue, split) {
            return pValue + split.get('amount');
        }, 0);
    })
    */
});
Run Code Online (Sandbox Code Playgroud)

失败的测试(预期1350,得到0):

import { test, moduleForModel } from 'ember-qunit';
import Transaction from 'my-app/models/transaction';

moduleForModel('transaction', 'Unit - Transaction Model', {
    needs: ['model:split']
});

test('amount', function() {
    var transaction = this.subject();
    var store = this.store();
    transaction.get('splits').addObjects([
        store.createRecord('split', { amount: 250 }),
        store.createRecord('split', { amount: 1000 })
    ]);
    equal(transaction.get('amount'), 1250);
});
Run Code Online (Sandbox Code Playgroud)

ppc*_*ano 5

您的hasMany属性是异步的,因此它是一个promise,其值必须可以使用then方法访问.

transaction.get('splits').then(function(splits) {

  split = store.createRecord('split', { amount: 250 }),
  splits.pushObject(split);

  split = store.createRecord('split', { amount: 1000 })
  splits.pushObject(split);

});
Run Code Online (Sandbox Code Playgroud)