Javascript Ember数据异步关系的聚合
我有一张由多个交易组成的发票,任何交易都有一个总金额作为最终结果,它来自两个值的乘积:数量和票价 我试图计算所有这些交易的总和 这是错误未捕获类型错误:无法读取未定义的属性“getEach” 我理解为什么会发生这种情况,总值还不存在(因为它还没有计算出来) 这是我的型号,具有功能Javascript Ember数据异步关系的聚合,javascript,ember.js,jsbin,Javascript,Ember.js,Jsbin,我有一张由多个交易组成的发票,任何交易都有一个总金额作为最终结果,它来自两个值的乘积:数量和票价 我试图计算所有这些交易的总和 这是错误未捕获类型错误:无法读取未定义的属性“getEach” 我理解为什么会发生这种情况,总值还不存在(因为它还没有计算出来) 这是我的型号,具有功能transactionsAmounts App.Invoice = DS.Model.extend({ title : DS.attr('string'), transactions : DS.
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")
我在这篇文章中重复了这个案例
我该怎么做?这是一个正在工作的js bin,修改了您的代码位: 您的问题在于您的模型声明中混合了一些东西:
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'), /
});
首先,查看您试图引用的模型的属性
或观察值
。@每个这对于阵列控制器
都是好的,但是您处于DS.model
:)中,观察的是事务
然而,那些事务是异步的,因此ember将加载一个“承诺”,从而使用“异步”javascript