What You Need to Know About the JavaScript Framework Knockout.js

Knockout is a JavaScript library that can be used to build rich and responsive editor user interfaces. It also enables developers to implement MVVM pattern on the client side in a clean fashion. It is not a library, which would replace the core JavaScript libraries like jQuery or coffee script; rather it is designed to work along with them.

Knockout JavaScript library can be downloaded from here and the good news is that the Asp.Net MVC 4 project templates bring Knockout JavaScript out of the box. In short Knockout JavaScript will be termed as KO.

In this article I will explain few of the basic binding features that can be accomplished using KO library.

MVVM Pattern

In a web application MVVM is nothing but the Model-View-ViewModel pattern, which helps in segregating the View and ViewModel on the client GUI layer. Here is a small essence about its constituents.

1. Model – The data for / from the UI.

2. View – The GUI elements, which are displayed on the client web page.

3. ViewModel – This acts as a bridge between the GUI and the data model. Also responsible for formatting, massaging or computing the data that is going to be bound to the View.

Code Sample

In the following sections I will be using the same View and ViewModel for demonstrating the binding features.

View

<p><strong>Expense Report</strong></p>
<p>Employee Name:<label></label></p>
<p>Expense in Rs:<label></label> 

ViewModel

ExpenseReportModel = function(){
     this.name = "Dave Sheppard";
     this.expense = 1000;
 }
 
 // Activates Knockout.js
 ko.applyBindings(new ExpenseReportModel());

In the above example in the ViewModel the ko.applyBindings is the line of code, which will initialize and activate the KO library features.

Knockout JavaScript GUI Bindings

In this section we will take a look at the code samples for different types of bindings that you can perform using the KO library. The KO binding basically works by using the HTML data attribute called data-bind.

Text Binding

The code sample will do a one way binding of the data onto the web GUI elements. Here is the View with read only controls ingraining the data-bind attribute to bind the respective properties from the ViewModel.

<p><strong>Expense Report</strong></p>
<p>Employee Name: <label data-bind="text: name"></label></p>
<p>Expense in Rs: <label data-bind="text: expense"></label>

ViewModel

ExpenseReportModel = function() {
     this.name = "Dave Sheppard";
     this.expense = 1000;
 }
 
 // Activates Knockout.js
 ko.applyBindings(new ExpenseReportModel());

Two Way Binding

This binding is required when you want to allow the users also to enter the model data and the same has to reflect in the ViewModel. The KO function observable() can be used for achieving it. In the View sample I have also changed the labels to input controls.

<p><strong>Expense Report</strong></p>
 <p>Employee Name: <input type="text" data-bind="value: name"></input></p>
 <p>Expense in Rs: <input type="text" data-bind="value: expense"></input> </p>
 Name of the employee <label data-bind="text: name12"></label>

In the ViewModel code modify the properties to use observable function as shown below.

ExpenseReportModel = function() {
     this.name = ko.observable("Dave Sheppard");
     this.expense = ko.observable(1000);
 }
 
// Activates Knockout.js
 ko.applyBindings(new ExpenseReportModel());

Run the application and as you enter the employee name and tab out of the textbox you will see that the label binding the name of the employee is also refreshing with the current value.

Computed Property

Using the KO library you can also create a computed property where a property can expose data by computing the values of other properties. I will now modify the sample code to compute the remaining budget for the employee.

<p><strong>Expense Report</strong></p>
<p>Employee Name: <input type="text" data-bind="value: name"></input></p>
<p>Expense in Rs: <input type="text" data-bind="value: expense"></input> </p>
<span>Remaining budget: <label data-bind="text: budgetRemaining"></label></span>

ExpenseReportModel = function() {
 this.name = ko.observable("Dave Sheppard");
 this.expense = ko.observable(1000);
 this.total = ko.observable(5000);
 this.budgetRemaining = ko.computed(function(){
         return this.total() - this.expense();
 }, this);
}
 
 // Activates Knockout.js
 ko.applyBindings(new ExpenseReportModel());

Fig 1.0 displays the computed remaining budget based on the entered expense amount.

The computed remaining budget
Fig 1.0: The computed remaining budget

Event Binding

We can also bind the events to the controls using the KO library. In the example below I will add the button and bind its onclick event to write a meaningful message.

<p><strong>Expense Report</strong></p>
 <p>Employee Name: <input type="text" data-bind="value: name"></input></p>
 <p>Expense in Rs: <input type="text" data-bind="value: expense"></input> </p>
 <input type="button" data-bind="click: onSubmitEvent" value="Submit"/>
 <p><label data-bind="text: message"></label></p>

ExpenseReportModel = function() {
    this.name = ko.observable("Dave Sheppard");
    this.expense = ko.observable(1000);
    this.total = ko.observable(5000);
    this.message = ko.observable("");
    this.budgetRemaining = ko.computed(function(){
         return this.total() - this.expense();
    }, this);
    onSubmitEvent = function(){
         this.message("Budget remaining for employee " + this.name() + " is " + this.budgetRemaining());
    }
 }
 
 // Activates Knockout.js
 ko.applyBindings(new ExpenseReportModel());

Fig 2.0 shows the output where the message is displayed on click of the button.

The output where the message is displayed
Fig 2.0: The output where the message is displayed

The above samples would indicate how useful it will be to use the KO library for making the client GUI rich, responsive and auto refreshing. There are many more advanced futures in the KO library like Templating, creating custom bindings, etc. I will cover those in future articles.

Happy reading!



Related Articles

Comments

  • Nice one there

    Posted by Slalaleasyday on 03/14/2013 09:46am

    Nice Post. ---------- I love http://youtube.com

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 23, 2015 @ 1:00 p.m. ET / 10:00 a.m. PT The cloud is not just about a runtime platform for your projects – now, you can do your development in the cloud, too. Check out this upcoming eseminar to learn how the cloud improves your development experience and team collaboration. Join Dana Singleterry, Principal Product Manager for Oracle Dev Tools, as he discusses how to simplify every aspect of the development lifecycle, including requirements gathering, version management, code …

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date