The following, renders: Subtotal: P[object Object]
It seems that subtotal is returning the promise object instead of th sum of all orders. VARIATION 2
also returns a promise.
How should I go about calculating the subtotal of all products?
// app/controllers/application.js
import Ember from 'ember';
export default Ember.ObjectController.extend({
subtotal: function() {
// VARIATION 1:
var productCollectionPromises = this.get('orders').getEach('product');
var sum = 0;
return Ember.RSVP.all(productCollectionPromises).then(function(productCollections){
productCollections.forEach(function(product){
sum += product.get('amountInCents');
});
return sum;
});
// VARIATION 2:
// return this.get('orders').mapBy('product').reduce(function(previousValue, product) {
// return previousValue + product.get('amountInCents');
// }, 0) / 100;
}.property('orders.@each.total'),
});
// app/templates/application.hbs
<br /><strong>Subtotal:</strong> ${{subtotal}}
Ember.RSVP.all
returns a promise, which is what you are returning, you can just make an observer and update subtotal
on change:
// app/controllers/application.js
import Ember from 'ember';
export default Ember.ObjectController.extend({
subtotal: null,
totalsChanged: function() {
var productCollectionPromises = this.get('orders').getEach('product');
var sum = 0;
Ember.RSVP.all(productCollectionPromises).then(productCollections => {
productCollections.forEach(function(product){
sum += product.get('amountInCents');
});
this.set('subtotal', sum);
});
}.observes('orders.@each.total'),
});