It's a Knockout: 2 - Simple Data Binding

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

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

image_thumb20

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

image_thumb23

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

image_thumb26

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

image_thumb29

This html and javaScript produces the following in the browser, as the value of the personName property is rendered in the span.

image

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.

Disclaimer

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

Tags