Saturday, June 28, 2014

Knockout.js

Knockout.js is a JavaScript library Which works on the principal of Model – View – View Model. It allows us to bind html elements of the view with data model. The best part of Knockout is it provides a simple two-way data binding between data model and UI element. In Simple Words if you make any change in the  data model then those changes will be automatically reflected in the DOM(UI) or if there are any changes done against DOM elements those will automatically reflected to the data model.  We can say that these are similar to the Binding features present in WPF.

Some of the Key benefits of Knockout are :

Ø  Bindings of UI elements with data model. 
Ø  Dynamic data model creation is simple.  
Ø  Knockout supports event-driven programming model.  
Ø  Cross browsers are support.

Knockout was developed and maintained by Steve Sandersona Microsoft employee. This is a Open Source product. We can get the Library or files from the Below mentioned Location.

Using nu-get 

To install knockout.js, run the following command in the Package Manager Console

PM> Install-Package knockout.js         
The Latest version is knockout.js 3.1.0. It is also available on the CDN at below mentioned location.


Sample Application in Knockout  Hello, Planet Earth!

 Create the Below  Two Text Box on the HTMl page.

First name: < input data-bind="value: firstName" />
Last name: < input data-bind="value: lastName" />

Hello, data-bind="text: fullName"> !



Use the Knockout binding as below. Note the Word KO is  the short-form of Knockout. Which is reserved for referring  Knockout object.

// create data model
var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);

    this.fullName = ko.computed(function() {

 // Binding will be take care by Knockout.

       return this.firstName() + " " + this.lastName();
    }, this);
};

// Relation will be bind by below satatement 
ko.applyBindings(new ViewModel("Planet", "Earth"));

You can download the sample application from Download. Please share your comments on the same. Will be happy to answer any doubts if you have. :)

 Thanks
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM



Kontera