javascript - Ember 数据异步关系的聚合

标签 javascript ember.js jsbin

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

我尝试计算任何交易的所有这些总数的总和

这是错误未捕获的类型错误:无法读取未定义的属性“getEach”

我明白为什么会发生这种情况,总值(value)还不存在(因为它还没有计算)

这是我的模型,具有函数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中重现了这个案例

我该怎么做?

最佳答案

这是一个工作的 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'), /
});

首先查看您尝试引用model.@each属性观察,这对于很有用ArrayController,但您处于 DS.Model 中:)您想要观察的是事务。

但是这些事务是异步的,因此ember将加载“promise”,从而使用“异步”javascript。

关于javascript - Ember 数据异步关系的聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771805/

相关文章:

javascript - Passport 身份验证不适用于 Node 中的 multer

Ember.js bindAttr 加明文

javascript - emberfire 1.3.2 是否实现了 findQuery 方法?

javascript - Ember View 中未显示的选项 选择可编辑

javascript - JS Bin while 无限循环

jsbin - 如何设置 JSBin 主题?

javascript - 与 HTMLElement 对象进行数据关联的最佳实践?

JavaScript:将对象绑定(bind)到 DOM 元素

javascript - 如何捕获鼠标悬停事件上的鼠标左键?

Ember.js - CircleCI - BrowserStack