Tuesday, 20 August 2013

Knockout: Knockout and MVVM pattern

Introduction:
Knockout.js is a javascript library that helps us to create rich and responsive use interfaces with a clean data model.

Features:
1. Declarative Bindings - A simple way to bind a part of UI to data model.
2. Dependency Tracking - Automatically updates right part of UI when data model changes.
3. Templating - A simple way to make nested UIs as a function of view model data.
4. Trivially Extensible - With a just few line of code, we can implement custom behaviors as new declarative binding for easy reuse.

Benefits:
1. Free and open source.
2. Pure javascript - works with any client side or server side technology.
3. Small and lightweight - 40kb, around 30kb after gzipping.
4. It has no dependencies.
5. It works with any mainstream browser ((IE 6+, Firefox 2+, Chrome, Safari, others).

 Knockout.js simplifies javascript UIs by applying the MVVM pattern.

What is MVVM pattern?
MVVM was originally defined by Microsoft for use with Windows Presentation Foundation (WPF) and Silverlight.

In recent years, MVVM has been implemented in JavaScript in the form of structural frameworks such as KnockoutJS, Kendo MVVM and Knockback.js.

Model-View-View Model (MVVM) is a design pattern to clearly separate the development of user-interfaces from  the business logic and behavior in an application.


A Model:
It is a set of classes representing the data comes from services or database. We usually make ajax call to some server side code to read or write the data.

A ViewModel:
It is a pure-code representation of the data and operations on a UI

We can write a View-Model just like declaring any javascript object:
var myViewModel = {
    personName: 'Rakesh',
    personAge: 123
};


A View:
A visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.

We can write it as HTML:
The name is <span data-bind="text: personName"></span>

It will display the output as:
The name is Rakesh

Activating Knockout:
Data-bind attribute - The data-bind attribute isn’t native to HTML, though it is perfectly OK (it’s strictly used in HTML 5, and causes no problems with HTML 4 )

We need to activate knockout to make data-bind attribute effect:
ko.applyBindings(myViewModel);


If you want to bind model to a part of view:
ko.applyBindings(myViewModel, document.getElementById('someElementId'));
ko.applyBindings(myViewModel, $('#someElementId')[0]);

Summary:
In this blog I explained the features and benefits of  knockout.js and how knockout.js facilitates MVVM pattern.


No comments:

Post a Comment