Thoughts from the Wet Coast

The musings of an ASP.NET Developer from Canada's We(s)t Coast

It's a Knockout: 4 - Two-way Data Binding

Category: JavaScript
Tags: knockout
Last Modified: May 2 2017
Aug 10 2013

So far in this series on Knockout.js we have seen how to do simple data-binding and how to use observables to automatically update the data bound elements.  The real power of knockout though is its support of two-way data-binding. 

What do we mean my two-way data-binding?

ASP.NET developers are familiar with the concept of data-binding - the ability to bind a control to a data source and update the control based on the value of the data source.  Two way data-binding allows the control (View) to update the data source if its value changes.

Lets continue with our example which we have been developing in the previous two posts to illustrate this.  In addition to the “text” binding we have been using in the previous examples, knockout also includes the “value” binding which can be used for input html elements - see Figure 1.

Figure 1: Adding an input element and using the value binding


In this example we are now binding the same personName observable to the input box’s value property.  Figure 2 shows the updated html when this new section is added to our previous example.

Figure 2: Two way data-binding example


If we run this in a browser, the span’s text will initially be set to the initial value of the observable (Bob), as will the input box’s value property.


However, as the input’s value is editable by the user, we can now change the value in the browser, and as soon as we move focus away from the input box the observable will be updated and all the elements bound to the observable will also be updated.


This is very powerful.  all we have done so far is define a ViewModel, with an observable property (personName) and define a View with two elements - a span and input - and set the data-binding attributes for the elements - knockout takes care of everything else.

There is still a lot more to knockout and in the next post I will introduce the concept of computed observables.


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