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/
You have two problems:
ko.observable
returns a function so you need to get its value with calling it as a function with ()
. For example: self.column1()
and self.column1()
this
inside a computed is not the "current" object so you should use self
instead (or pass this
as the second argument of ko.computed
)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.