Search code examples
jqueryknockout.jsknockout-2.0knockout-mvc

Update the entire row after changing 1 column + Knockout.js


I have a observable array, with a list of values, every value has a percent calculated by :
100 * valueQuantity / valuetotal.

valueQuantity = input value
valueTotal = value0 + value1 + value2

If the user changes a value, the valuetotal needs to change and a recalculation has to be performed for the values (value0, value1 and value2) in the selected row.

I am using an extender to calculate the percent.

sample : JS fiddle sample

I need to update the values after changing a value in the table.


Solution

  • Each value you need in the calculation that can be changed needs to be a ko.observable in the model. For example:

    { name: "CEP 7", value0: ko.observable(50), percent0: 0, value1: ko.observable(50), percent1: 0, value2: ko.observable(20), percent2: 0 },
    

    Whichever value should be computed, should be a ko.computed value, not an observable. For example:

    percent0: ko.computed(function() {
        return this.value0() / (parseFloat(this.value0()) + parseFloat(this.value1()) + parseFloat(this.value2()));
    }),
    

    Then your binders should "just work". Your use of declaring ko.observables in the markup seems unusual.