knockout.jscalculated-columnscomputed-values

Error with sum up values in a row using knockout.js and ko.computed


I think this a really basic problem but I just don't see the error. I got the following simple Model:

var Row = function(col1, col2)
{
    var self = this;

    self.column1 = ko.observable(col1);
    self.column2 = ko.observable(col2);
    self.sum = ko.computed(function(){
        var col1 = isNaN(parseInt(this.column1)) ? 0 : parseInt(this.column1);
        var col2 = isNaN(parseInt(this.column2)) ? 0 : parseInt(this.column2);

        return col1 + col2;
    });
}


var RowViewModel = function()
{
    this.rows = ko.observableArray([
        new Row(10, 20),
        new Row(10, 20)
    ]);
}

 ko.applyBindings(new RowViewModel);

As you see I only want to sum up two values within a table row using the ko.computed function. But it always shows me NaN (if I don't check for it) or "0". I really tried a lot, but I can't figure out what the problem is. Over here is my jsfiddle: http://jsfiddle.net/r2JQw/4/


Solution

  • You have two problems:

    So the fixed sum would look like this:

    self.sum = ko.computed(function(){
        var col1 = isNaN(parseInt(self.column1())) ? 0 : parseInt(self.column1());
        var col2 = isNaN(parseInt(self.column2())) ? 0 : parseInt(self.column2());
    
        return col1 + col2;
    });
    

    Demo JSFiddle.