Question

I'm working with an observable array of "Parts" that contains an observable of "Vol". I currently have the volume of each part as well as the total amount displayed. When the application starts the total amount is added correctly. However, when I change the volume of a part the total amount doesn't get recalculated.

HTML:

<ul>
    <li data-bind="foreach:  Parts">
        <input data-bind="value: Vol" />
<br/>
    </li>
</ul>

<br/>
<br/>
<span data-bind="text: fullVol "></span>

Javascript:

    function Part (data) {

       var self = this;
        self.Vol= ko.observable(data.Vol);

    }


    function AppViewModel() {
       var self = this;


        self.Parts = ko.observableArray([new Part({"Vol": 1}), new Part({"Vol":2}), new Part({"Vol":3})]);
        self.fullVol = ko.computed(function() {
            var total = 0;
           $.each(self.Parts(), function() { total += (this.Vol() ) })
            return total;
        });
    }


ko.applyBindings(new AppViewModel());

Here is my JsFiddle: http://jsfiddle.net/jwinstonaspen/Zmkew/6/

Was it helpful?

Solution

When you use the value: Vol binding knockout won't convert your input to integer just stores the user entered data as a string.

So you need to parse it to integer before calculating the total:

$.each(self.Parts(), function() { total += (parseInt(this.Vol()) ) })

A fixed fiddle.

Now because you are doing the parsing you should not forget to deal with when case the user enters a non numeric input.

However you can easily write an custom binding handler which abstracts away the parsing.

Or you can do with using ko.extenders. The documentation has an example as well here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top