1

我有一张由更多交易组成的发票,任何交易都有一个总金额作为最终结果,它来自两个值的乘积:数量和票价

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

这是错误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中复制了这个案例

我该怎么做?

4

1 回答 1

1

这是一个修改了您的代码位的工作 js bin: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', 'transactions.@each.total'), /
});

首先看一下,property或者observes你尝试引用model.@each这对一个有好处ArrayController但你在一个DS.Model:) 你想要的observes是交易。

然而,这些transactions是异步的,因此 ember 将加载“承诺”,从而使用“异步”javascript。

于 2015-01-05T01:50:50.913 回答