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();