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
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
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.
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.