In the first part of this blog series on Knockout.js, I introduced the MVVM (Model-View-ViewModel) nature of the framework. In this second post I will show how Knockout’s data-binding works.
Lets start with a simple example. First we will define a ViewModel that we will bind to our View.
Figure 1: Defining a simple ViewModel
This is a very simple ViewModel - an object with a single property - personName, with a value of ‘Bob’.
Next we need to create a View.
Figure 2: Defining a simple View
In this view we have a span with a data-bind attribute. The data-bind attribute is what makes everything work. It is part of the HTML 5 spec but is ignored by browsers which do not support HTML 5. Knockout, regardless of browser uses the data-bind attribute to determine what to bind. In this case the personName property of our ViewModel will be bound to the text property of the span element.
So, now we have defined our ViewModel and our View - how do we make them bind to ach other. Just like with server-side data binding Knockout provides a “data bind” method, in this case it is called applyBindings() (see Listing 3)
Figure 3: Binding the ViewModel to the View
ko is the knockout object which is defined in the knockout framework, and the applyBindings method takes the ViewModel as a parameter.
We can put the whole thing together - (see Figure 4)
Figure 4: Simple Data Binding example
This was a very simple example of one way data binding. Knockout can do much more, and in the next post in this series I will introduce the concept of observables, which provides Knockout with its power as a two way data-binding framework.