It's a Knockout: 5 - Computed Observables

Category: JavaScript
Last Modified: May 2 2017
Aug 15 2013

So far we have seen how we can set up simple observable values.  But what if we want to have calculated values in our ViewModel.

Lets extend our ViewModel from the previous examples, by renaming our personName property as firstName and add a second property called lastName.

image

Now lets say that we want to display the full name of person.  Knockout provides the computed method, which we can then bind to our View.

Figure 1: A Computed Observable

image

Note that because JavaScript functions do not belong to an object - like they do in C# or Java, if we want to use “this” inside the function we should pass it in as the second parameter of the computed method.  Alternatively as we are using an internal reference to this by assigning the variable self to this in the constructor, we can simplify our use of the computed function as shown in the full listing.

Figure 2: Computed Observables Example

image

In the full example the firstName and lastName properties are bound the value property of the input element, and the computed observable fullName is bound to the text property of the span.

image

If either of the observable properties are updated the computed observable is also updated and anything bound to it is also updated.image

Computed observables add a lot of flexibility to Knockout applications.  So far, we have looked at simple observables and computed observables and we have reviewed simple data-binding and two-way data-binding. 

In the next article I will introduce the idea of observable arrays so we can bind collections of items.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Tags