Saturday, February 1, 2014

What is Model View View Model (MVVM) pattern? Implement it with Knockout JS

Recently we tried our hands on PhoneJs, a JavaScript framework to build cross platform application. It usese jQuery and Knockout JS and it implements MVVM design pattern.

Model View View Model - MVVM is a design pattern to build an application. It was first introduced by Microsoft and it's widely used by Microsoft Silverlight and WPF (Windows Presentation Foundation) developers. We will not go in that detail But we will see how it is implemented with Knockout JS.

First lets see the elements of MVVM pattern

Model

Model represents the business entity. It's your application's stored data. Model just stores the data. It's independent of user interface. It does not handle how the data will behave and represented on user interface. In short it encapsulates application data. This data can be used by ViewModel. ViewModel can update/add/delete data. In Knockout JS any valid JavaScript object can represent Model.

For example : 

var person = {
      firstName: 'Hiren',
      lastName: 'Dave'
};

Above is the valid Knockout JS model. Also we can define datasource that fetch data from remote URL as Model.

View

View is the visual representation of model. However it does not interact with models directly. It just describes the format and events. It also defines the bindings for the data source. It pass on events to ViewModel and receive response from ViewModel. It's independent of business logic described in ViewModel. It updates it self when it receives data from ViewModel. With Knockout JS  View is the plain HTML file. For example.

<div> My name is <span data-bind="text: firstName" /> <span data-bind="text: lastName" /> </div>

ViewModel

ViewModel is special type of controller which that converts the data for the view. It passed command from Model to View and View to Model. It defines event handlers for the View. It converts model information to view information. It also exposes methods to maintain view's state, updates model based on view states and updates views for change in Model. For example,

ko.applyBindings(person);

Above code will tell View to apply binding and transfer person model to view. View will show the data from specific object properties as mentioned in View. In this case it is firstName and lastName.

This is how Knockout JS works.






No comments:

Post a Comment