Computed observables are functions that can "watch" or "react" to other observables on the view model. The following example shows how you would display the total number of users and the average age.
Note: The example below can also make use of pureComputed() (introduced in v3.2.0) since the function simply calculates something based on other view model properties and returns a value.
<div>
Total Users: <span data-bind="text: TotalUsers">2</span><br>
Average Age: <span data-bind="text: UsersAverageAge">32</span>
</div>
var viewModel = function() {
var self = this;
this.Users = ko.observableArray([
{ Name: "John Doe", Age: 30 },
{ Name: "Jane Doe", Age: 34 }
]);
this.TotalUsers = ko.computed(function() {
return self.Users().length;
});
this.UsersAverageAge = ko.computed(function() {
var totalAge = 0;
self.Users().forEach(function(user) {
totalAge += user.Age;
});
return totalAge / self.TotalUsers();
});
};
ko.applyBindings(viewModel);