我有一张由更多交易组成的发票,任何交易都有一个总金额作为最终结果,它来自两个值的乘积:数量和票价
我试图计算所有这些交易的总和
这是错误Uncaught TypeError: Cannot read property 'getEach' of undefined
我明白为什么会发生这种情况,总价值还不存在(因为它还没有计算出来)
这是我的模型与功能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('model.@each.total'),
});
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("totals.@each.total")
我已经在这个jsbin中复制了这个案例
我该怎么做?