如果我有一些这样的模型
App.Transaction = DS.Model.extend({
amount: DS.attr('number'),
type: DS.attr('string')
});
其中类型可以是“VISA”或“Mastercard”或“Cash”之类的内容。我有一个计算属性,可以计算所有交易的总金额。
totalAmount:function() {
return this.getEach('amount').reduce(function(accum, item) {
return (Math.round(accum*100) + Math.round(item*100))/100;
}, 0);
}.property('@each')
我想要做的是创建另一个计算属性,该属性返回按类型分组的所有交易的总金额(例如,类型==“VISA”的所有交易的总金额)。
如何在 Ember js 中执行此操作?是否有 getAll 方法或某种方式来获取我可以过滤的数组中的所有事务对象?
最佳答案
Ember.Array类具有 filterProperty 方法,可以为您执行此操作。您可以像这样专门调用它:
visaTotalAmount: function() {
return this.filterProperty('type', 'VISA').getEach('amount').reduce(function(accum, item) {
return (Math.round(accum*100) + Math.round(item*100))/100;
}, 0);
}.property('@each')
这将仅过滤掉 VISA 类型并像之前一样进行总计算。
关于ember.js - Ember 数据过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15058495/