2013-07-01 204 views
1

我想用Ember ObjectController創建一些計算屬性,並遇到一些困難。我的對象(Baz)包含一個對象數組(Foo)。每個Foo都有一些鍵/值對,我們稱它們爲alpha和beta。Ember.JS計算屬性

使用這樣的代碼:

App.BazController = Ember.ObjectController.extend({ 
    total: function() { 
     return this.get('foos').getEach('alpha').reduce(function(accum, item) { 
      return accum + item; 
     }, 0); 
    }.property('[email protected]') 
}); 

我可以計算出每一個Foo對象的「阿爾法」屬性的總和,但我想計算具體FOOS之間的值,最好通過其內置的ID選擇。我嘗試了各種各樣的表達式來嘗試從數組中選擇一個單獨的Foo對象,但我似乎無法弄清楚。

這可以在一個ObjectController中完成,或者這是錯誤的地方去嘗試和計算這些值嗎?

從代碼到概念演練的任何幫助將不勝感激。

乾杯, 艾倫

回答

2

您可以在reduce方法訪問item的性能,同時建立了total。例如,要找到產品的總數,但只有它們是inStockonSale,才能使用。

totalByReduce: function() { 
    return this.get('model').reduce(function(total, product) { 
    if (product.get('inStock') && product.get('onSale')) { 
     return total + product.get('price'); 
    } else { 
     return total; 
    } 
    }, 0); 
}.property('[email protected]') 

同樣,如果你正在做的濾波在多個階段,即: - 過濾然後還原,可以具有取決於相互2種不同的計算性能。舉例來說,如果你只顯示產品是inStockonSale

saleProducts: function() { 
    return this.get('model').filter(function(product) { 
    return product.get('inStock') && product.get('onSale'); 
    }); 
}.property('[email protected]'), 

然後拿到saleProducts你可以設置一個第二個計算的財產像total

total: function() { 
    return this.get('saleProducts').reduce(function(total, product) { 
    return total + product.get('price'); 
    }, 0); 
}.property('[email protected]'), 

這裏有一個jsbin例子。

相關問題