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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds