Knockout: Computed fields

Using Knockout.js to dynamically aggregate fields.

Many times when working on the presentation layer of an application the need arises to present a value which is the result of aggregating the values of two or more fields.
In this article I will illustrated how to combine the values from three fields and assign it as the value from a new field.

I’ll begin with HTML for both name fields and one field to represent a sales associate’s revenue.
Also, I’ll one more field which I’ll use to assign the computed values of the first three fields.

1-knockout-computed-fields

In order to have my ViewModel notified of changes and have its properties updated with those changes, I’ll assign observables to each property.
Also, I’ll use the “computed()” function to grab the values from the firstName, lastName, and SalesRevenue controls to aggregate a new value which is then assigned to the SalesAssociateOverview property.
In order to format the Sales Revenue appropriately, I applied a currency format.

2-knockout-computed-fields

When my page loads, the default values are aggregated together and assigned to the SalesAssociateOverview property.

3-knockout-computed-fields

When I change each fields, the observables ensure my ViewModel’s properties are notified and my computed value is updated accordingly.

4-knockout-computed-fields

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s