2015-01-05 47 views
1

我有更多的交易组成的发票,任何事务都有一个总金额为最终结果是来自两个值的乘积:量和票价聚集了灰烬数据异步关系

我尝试计算所有这些总的交易

这的总和是错误遗漏的类型错误:无法读取属性“getEach”的未定义

我理解为什么会这样,该值总量不EXI ST还没有(因为它不是仍然计算)

这是我的模型与功能transactionsAmounts

App.Invoice = DS.Model.extend({ 
    title   : DS.attr('string'), 
    transactions : DS.hasMany('transaction', { async:true}), 
    transactionsAmounts: function() { 
    var sum = function(s1, s2) { return s1 + s2; }; 
    return this.get('model').getEach('total').reduce(sum); 
    }.property('[email protected]'), 
}); 

App.Transaction = DS.Model.extend({ 
    quantity: DS.attr('string'), 
    fare: DS.attr('string'), 
    total: DS.attr('string'), 
    invoice: DS.belongsTo('invoice'), 
    updateTotal: function() { 

    // get the reference to the values of fare and quantity 
    var quantity = this.get('quantity'), 
     fare = this.get('fare'); 

    // massage them to make sure your stuff is not gonna break 
    if (isNaN(fare)) { fare = 0; } 
    if (isNaN(quantity)) { quantity = 0; } 

    // calculate 
    var total = fare * quantity; 

    // set the total 
    this.set('total', total); 

}.observes('quantity', 'fare') 


}); 

这是我用来计算所有汇总的其他功能,我也得到了同样的错误

transactionsAmounts: function(){ 
    var totals = this.get("total"); 
    return totals.reduce(function(previousValue, total){ 
     return previousValue + totals.get("transactionsAmounts"); 
    }, 0); 
}.property("[email protected]") 

我纷纷转载这个jsbin

的情况下,我该怎么办呢?

回答

1

这里是你的代码位工作JS斌修改:http://jsbin.com/lipakamasi/18/edit?js,console,output

你的问题是在你的模型声明中,你是混合一些东西:

App.Invoice = DS.Model.extend({ 
title   : DS.attr('string'), 
transactions : DS.hasMany('transaction', { async:true}), 
transactionsAmounts: 0, 
setTransactionAmount : function(){ 
    if(this.get("transactions.length")>0){ 
     this.get("transactions").then(function(transactions){ 
     var sum=0; 
     transactions.forEach(function(transaction){ 
     sum+=transaction.get("total"); 
     }); 
     this.set("transactionsAmounts",sum); 
    }.bind(this)); 
    } 
    }.observes('transactions.length', '[email protected]'),/
}); 

首先看在propertyobserves你试图参考[email protected]这是一个很好的ArrayController,但你在DS.Model :)你想observes是交易。

但是那些transactions是异步,因此烬将加载一个“承诺”,从而与“异步”的JavaScript工作。