It's a Knockout: 3 - Observables

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

In the previous post in this series I introduced the concept of simple one-way data binding.  However the real power of knockout is its support of observables and two-way binding. 

The concept of observable objects or observable collections was developed for WPF (Xaml) and Silverlight. 

The idea is that an observable object can monitor when a property has changed so that all the items bound to the property can be updated.  In the Xaml world an observable class implements the INotifyPropertyChanged Interface, and an observable collection implements INotifyCollectionChanged as well as INotifyPropertyChanged. 

These interfaces “notify” anything bound to the property that the property (collection) has been changed and in Xaml the control updates itself.

Knockout’s support of observables is similar.  Lets update our previous example to use observables.

Figure 1: Updating the ViewModel to use Observables

image

In Knockout an observable is a set of a JavaScript functions.  To read (get) the value of the observable just call the function with no parameters - in this case myViewModel.personName(), to write (set) the value just call the function with a single parameter representing the new value - in this case myViewModel.personName(‘Fred’).

To demonstrate how observables dynamically update the View which is bound to the ViewModel, lets further modify the example from the previous post, as shown in Figure 2.

Figure 2: Updating the View by updating an Observable

image

Note that we don’t need to update the View - the data-bind attribute still “binds” to the observable property.  All we have done is convert personName to an observable and to add a statement updating the value of the observable to “Fred”.

When run in a browser the span now renders Fred.

image

This example demonstrates the power of observables.  We just need to update the value in code - and the View will be immediately updated.  But we are still just doing one-way binding.  In the next post in this series I will show how knockout can be used to support two way binding.

Disclaimer

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

Tags