我的应用程序有一个名为 Balance 的模型,我们可以在其中添加金额和说明。我创建了一个操作,当您单击按钮时添加一些余额记录,到目前为止效果很好。问题是我创建了一个名为“totalBalance”的 Controller 属性来检索和计算数据库中的总金额,它工作得很好并且显示在页面中,但当我添加新记录并且我希望它更新时它不会更新实时更新。
这是我的代码:
平衡 Controller
App.BalanceController = Ember.ArrayController.extend({
totalBalance: function() {
var total = 0;
this.store.all('balance').forEach(function(item) {
total = total + item.get('amount');
});
return total;
}.property('balance.@each'),
actions: {
generateBalance: function() {
var balance = this.store.createRecord('balance', {
amount: 1270.84,
description: 'Some dummy description for this balance.'
});
balance.save();
}
}
});
平衡模型
App.Balance = DS.Model.extend({
amount: DS.attr('number'),
description: DS.attr('string')
});
平衡路线
App.BalanceRoute = Ember.Route.extend({
model: function() {
return this.store.find('balance');
}
});
最佳答案
我认为问题在于您为totalBalance指定依赖键的方式。我会尝试做这样的事情:
App.BalanceController = Ember.ArrayController.extend({
totalBalance: function() {
var total = 0;
this.forEach(function(item) {
total = total + item.get('amount');
});
return total;
}.property('content.@each.amount')
});
作为一个更简洁的选项,您还可以使用 reduceCompulated
属性来指定执行的总和 here .
关于javascript - EmberJS 属性在创建记录时不会自动更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21218548/