Jun 17, 2013

Enhancing Web Development with Knockout.js

Austin Christenberry

Austin Christenberry

Default image background

Today, we will explore the popular JavaScript framework called Knockout – what it is, how to leverage it to enhance your web development and some tips-n-tricks to make it easy.

Background History

When jQuery was released in 2006, writing client-side JavaScript became much easier – this JavaScript library offers cross-browser support and simpler syntax for handling DOM manipulations, CSS, events, etc. As such, more and more developers have shifted to developing applications with rich client-side functionality. However, sometimes jQuery alone is not enough. Recent years have seen the rise of Model-View (MV*) JavaScript frameworks, which allow developers to build truly sophisticated yet maintainable client-side applications. The number of mainstream MV* JavaScript frameworks is currently over 20, and growing. Popular choices include Backbone, Ember, and AngularJS, among several others. This post focuses on building an interactive ASP.NET application with another popular option: Knockout.

What is Knockout?

Knockout is a JavaScript library that uses a Model-View-ViewModel (MVVM) architecture that makes it easy for developers to create dynamic and interactive user interfaces (UI) with a logical underlying data model. Knockout’s website lists four key concepts:

1)    Declarative Bindings: Easily associate DOM elements with model data using a concise, readable syntax.

2)    Automatic UI Refresh: When your data model’s state changes, your UI updates automatically.

3)    Dependency Tracking: Implicitly set up chains of relationships between model data to transform and combine it.

4)    Templating: Quickly generate sophisticated, nested UIs as a function of your model data.

Note: This post does not delve into comparisons between Knockout and other MV* frameworks. If you are interested in determining which framework is best for your project, TodoMVC offers a downloadable application implemented in most of the popular frameworks in order to make your decision easier.

Building the Application

Let’s say you’re working for a company that owns several restaurants, and they need an application that allows them to edit information for existing restaurants and add new restaurants. I’ve created a simple ASP.NET web application that uses Knockout in order to do this:

As you can see in Figure 1, this page enables the user to enter relevant information about the restaurant, such as its name, address, and menu items. Below, Figure 2 shows the page once the relevant data has been entered and saved:



Figure 2**: The same page once information has been entered and saved

Transform your business operations with our Microsoft solutions

Explore Our Microsoft Consulting Services  →

The Knockout View Model and Data-Binding

Each of these entry fields (name, genre, etc.) is a property of the Knockout View Model:


Figure 3**: The View Model for the Restaurant page

Notice in Figure 3 that many of the properties are marked with ko.observable. This means that when elements on the page are “bound” to these properties (called Observables), the changes are picked up by the View Model and the UI can update automatically. The syntax to bind properties of HTML elements to Observables is simple (see Figure 4):

You can also use the Knockout “foreach” binding to easily display items in a collection.


Figure 4**: The value of this textbox is bound to the “RestaurantName” property of the View Model

You can also use the Knockout “foreach” binding to easily display items in a collection.

Figure 5**: This code segment uses Knockout foreach binding to display a collection of Menu Items

The binding in Figure 5 results in a table of Menu Items with a row for every item in the array.

Automatic UI Refreshing

Here’s where it gets cool. I’ve mentioned the fact that Knockout allows the UI to refresh automatically but haven’t yet shown it in action. If you look back at Figure 1, you’ll notice that the Save button is disabled – this is because its “enable” attribute is bound to a Computed Observable called IsValid (see Figure 6).



Figure 6**: Also note that more than one attribute can be bound to the View Model

A Computed Observable, at the risk of sounding redundant, is an Observable that is computed, generally on other Observables. As Figure 7 shows, the IsValid Computed Observable will be true if all the fields have been entered, and false if at least one has not been entered.


Figure 7**: Computed Observable to determine whether the form is valid

This means that the Save button will be disabled until all the fields have been entered, when it will then automatically become enabled (see side-by-side comparison below in Figure 8, where the screenshot on the left is missing the Zip Code and the screenshot on the right is complete).


Because Knockout enables the UI to refresh automatically, it’s also much easier to create dynamic collections of objects with Knockout than with only jQuery. In this application, the click event of the “Add Menu Item” hyperlink is bound to a function that adds a new Menu Item object to the Menu Item’s array (see Figure 9).


The result of this is that when the user clicks “Add Menu Item,” a new row in the Menu Items table automatically appears – and only a few lines of code were required.

Parting Gift

If you’re developing an application with Knockout.js, then always be sure to include this line of code in your HTML when debugging (see Figure 10):


This will render the Knockout View Model as JSON on the page you’re working with and will save you many hours of debugging (see Figure 11).


Figure 11**: The rendered JSON of the Knockout View Model

Have you had a chance to test out Knockout.js? Do you prefer a different framework? Share your comments or questions concerning Knockout.js in the comment section below or send a tweet to @CrederaMSFT.

Conversation Icon

Contact Us

Ready to achieve your vision? We're here to help.

We'd love to start a conversation. Fill out the form and we'll connect you with the right person.

Searching for a new career?

View job openings