Friday, 1 March 2013


After a long time again back with some web apps stuffs and got time to share my studies on Knockout JS a JavaScript library.

Introduction to Knockout:

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

  • Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.
  • Pure JavaScript library - works with any server or client-side technology
  • Can be added on top of your existing web application without requiring major architectural changes
  • Compact - around 13kb after gzipping
  • Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms
For more information you can refer here.


This blog will gives you a glance at what is Knockout, why to use it and how to use it. If you are a newcomer to KO or if you are juggling between multiple JS libraries, this cheat-sheet is a handy guide to get your KO karma flowing.

  • Knockout is a JavaScript Library (as opposed to Backbone.js which is a framework) that helps you improve the User Experience of your web application. 

  • Knockout provides two way data-binding using a ViewModel and provides DOM Templating, it doesn’t deal with sending data over to server or routing.

  • You use Knockout as a drop-in enhancement library to improve usability and user experience, whereas Framework like Backbone is used ground up in new applications (Single Page Apps is a good example).

  • You can create a KO ViewModel as a JavaScript object or as a Function (known as prototype). It’s outside the jQuery document ready.

  • ViewModel as a function
                   var myViewModel = function() {
                              this.Email = “”;
                              this.Name = “Sumit”;
                              this.LastName = “Maitra”;
                              this.WebSite = “”; }

  • ViewModel as an object: you can follow the JavaScript Object Notation –
                var myViewModel = {
                            Email: “”,
                            Name: “Sumit”,
                            LastName: “Maitra”

  • Observable Properties are functions: When dealing with observable values you have to end the property with parenthesis like a function call, because computed values are actually functions that need to be evaluated on bind.
  • Applying a ViewModel
              // In case the View Model is defined as a function
                    ko.applyBindings(new orderViewModel());
              // In case the View Model is defined as a JSON Object

             Here ko is the global reference to Knockout that you get once you add Knockout                                                  Script reference in your page.

  • Observable Properties: KO has the concept Observable properties. If you define a property as an observable, then DOM elements bound to it, will be updated as soon as the property changes.
                   var myViewMode = {
                                 Email: ko.observable(“”)

  • Observable Arrays: When you define an array of Json objects as Observable, KO refreshes DOM elements bound to it when items are added or removed from the Array.
                           var orderViewModels = function() {
                                 // Binds to an empty array
                                  this.Address = ko.observableArray([]);

          Note: When properties of an Item in the array changes then KO does not raise ‘modified’ events.

  • Assign value to observables: We saw how to declare observable Properties above. But when we have to assign a value to an observable in JavaScript we assign it as if we are calling a function, for 

  • Simple Data Binding to properties
                  <input data-bind=“value : Email” />
                  Value of input element to the Email in the ViewModel.

  • Binding to Computed Values: Binding KO to a function gives you added flexibility of defining methods that do computation and return a computed value. KO can actually bind DOM elements to these methods as well.
       For example if we wanted to bind First Name and Last Name and show it in a single    DOM element we could do something like this:
On the View Model

                        var myViewModel = function() {
                        this.Email = “”;                        this.Name = “Sumit”;                        this.LastName = “Maitra”;                        this.FullName = ko.computed(function () {                        return this.LastName() + “, ” + this.Name();                        }, this);                        }

       Binding to DOM Element

                        <label data-bind= “text: FullName” />
  • Binding to an array of objects: KO can bind the DOM to an array in the view Model. We use KO’s foreach syntax as follows
                        <table>                        <tbody data-bind= “foreach: Address”>                                                </tbody>                        </table>

        You can do the same for an Ordered <ol> List or an Unordered List <ul> too. Once you have done the foreach binding, KO treats anything DOM element inside as a part of a template that’s repeated as many times as the number of elements items in the list to which it is bound.
  • Binding elements of an array: Once you have bound an Array to a DOM element KO gives you each element in the array to bind against. So an Address object may be bound as follows:
                        <table>                        <tbody data-bind= “foreach: Address”>                        <tr> <td>                        Street: <label data-bind: “text: Street” />                        #: <label data-bind: “text: Number” />                        City: <label data-bind: “text: City” />                        State: <label data-bind: “text: State” />                        </td> </tr>                        </tbody>                        </table>
  • Binding to properties other than text and value: Now let’s say we want to bind the WebSite element of the ViewModel an anchor tag
                        <a data-bind=“attr : {href : WebSite}”>                        <span data-bind= “text: Name”</a>

      What we are doing here is using Knockout’s attribute binding technique to bind the ‘href’ attribute to the URL in the WebSite property of the View Model. Using attribute binding we can bind to any HTML attribute we Observable Properties: KO has the concept of want to.

  • Getting KO Context in jQuery: Now let’s say we want to have a Delete button for each address. The following markup will add a button 
                        <table>                        <tbody class=“addressList” data-bind= “foreach: Address”>                        <tr><td>                        Address: <label data-bind: “text: $parent.                        AddressString(Street, Number, City)” />                        </td> <td>                        <button class= “addressDeleter” ></button>                        </td> </tr>                        </tbody></table>

Now to handle the click even using jQuery. Since the button is generated on KO binding we cannot use the normal click handler assignment of jQuery. Instead we use the parent container and assign a delegate as follows

                        $(“#addressList”).delegate(“.noteDeleter”, “click”,                        function() {                        var address = ko.dataFor(this);                        // send the address to the server and delete it                        });

As we can see above the ko.dataFor(this) helper method in KO returns the object that was bound to that particular row of data. So it returns an Address object. If you need the entire ViewModel you can use ko.contextFor(this).

Thanks for reading.Happy coding!!!!

1 comment:

  1. There are syntax errors all over this document. Please review your markup.