Question

Background:

I'm building my first web-app, a gradebook. I'm trying to calculate the average score from an observable array of scores. The average, called mean is an observable object. Both mean and scores belong to the model.

I'm just not sure what the problem here is. I noticed while printing mean to the console that the value printed is NaN OR a code block. My script as well as the console logs can be seen here:

http://jsbin.com/fehoq/20/edit

I'm wondering if adding a number to an observable isn't as straightforward as I'm assuming, but I'm not sure what the correct method would be instead.

Was it helpful?

Solution

When dealing with observables and observable arrays, make sure you read and write to them properly...

In this block of code...

this.scores = ko.observableArray([79, 89]);
this.mean = ko.observable();

// ...

ko.utils.arrayForEach(_this.scores(), function (score) {
    _this.mean += score;
    console.log(score);
    console.log(_this.mean);
});
_this.mean = _this.mean / _this.scores.length;
console.log(_this.mean);
return _this.mean;

_this.mean += score overwrites the original observable. Instead it should be _this.mean(_this.mean() + score). This happens in a couple of place.

Same goes for accessing the scores observable array. _this.scores.length should be _this.scores().length.

Here is the code with the changes applied...

ko.utils.arrayForEach(_this.scores(), function (score) {
     _this.mean(_this.mean() + score);
     console.log(score);
     console.log(_this.mean());
});
_this.mean(_this.mean() / _this.scores().length);
console.log(_this.mean());
return _this.mean();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top