0

My app have a model called Balance where we can add the amount and description. I created an action to add some balance records when you click on a button and it works great so far. The problem is that I created a controller property called "totalBalance" to retrieve and calculate the total amount from the database, it works great and it shows in the page but it don't update when I add a new record and I want it to update in real time.

Here's my code:

Balance 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();
        }
    }
});

Balance Model

App.Balance = DS.Model.extend({
    amount: DS.attr('number'),
    description: DS.attr('string')
});

Balance Route

App.BalanceRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('balance');
    }
});
Rafael Fragoso
  • 1,299
  • 1
  • 13
  • 21

1 Answers1

2

I think the problem is the way you specified the dependent key for totalBalance. I'd try doing something like this:

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')
});

As a somewhat cleaner option to this, you can also use a reduceComputed property for specifying the sum like performed here.

Community
  • 1
  • 1
Adam
  • 3,148
  • 19
  • 20