digital-pollution
digital-pollution

Reputation: 1074

knockout.js observable only updates on array push

I'm in the mist of learning knockout and am stuck on some functionality

I have an observable to calculate totals from values in an Observable array. Unfortunately it is only updating on push or remove, but I want it to also update on replace and when I update an attribute of one of the objects in the array, is there some way to manually trigger the update?

        self.basketTotal = ko.observable();
        self.basketItems = ko.observableArray([]);

        self.getTotals = ko.computed(function(){
             var total = 0;
             ko.utils.arrayForEach(self.basketItems(), function(item) {
                 total += parseFloat(ko.utils.unwrapObservable( parseInt( item.productPrice() )) );
             });
            self.basketTotal(total);
        });

Upvotes: 1

Views: 56

Answers (1)

digital-pollution
digital-pollution

Reputation: 1074

@super cool 's comment on the inital post was the right answer

"why you need a additional observable to store total ? directly return the total & bind the getTotals to view . coming to your updating part it should go smooth . sample with your issue would be helpful . FYI item.productPrice() does the unwrapping no need of unwrapObservable keep it simple like this ` total += parseFloat(item.productPrice());"

             var total = 0;
             ko.utils.arrayForEach(self.basketItems(), function(item) {
                 total += parseFloat( parseInt( item.productQtyPrice() ) );
             });

            self.basketTotal(total);

To answer the question about the additional observable, I'm using it to calculate all sorts of things like discounts and tax etc so theres a few steps in between excluded from the sample code to make the problem at hand a bit clearer, the issue at hand was simply the wrong calculation was being done (technically it was working code) and super cools comment helped to point that out.

Upvotes: 1

Related Questions