A Techno Blog, mainly about Java

Knockout jQuery

In the GWT ecosystem , the Model View Presenter (MVP) pattern is the architecture of choice. However, the model requires some special capabilities when  dealing with the state (i.e. what the user did should force some special visibility rules).

In MVP the model typically refers to just the domain objects that will be displayed, things like a Customer, Contact or Account. From a Presentation Model perspective the term model encompasses the domain data plus all additional state that can change during the normal operation of the UI.

Likewise, pure javascript libraries have to deal with these type of issues too. They have a name for the MVP + (Editors/Pectin) pattern.  Its called MVVM.

Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it’s displaying).

Knockout  handles data binding :  “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)”.

A simple example always explains it best.

The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.

For example, let us imagine that we have a model containing a date attribute in unix format (e.g 1333832407). Rather than our models being aware of a user’s view of the date (e.g 04/07/2012 @ 5:00pm), where it would be necessary to convert the address to it’s display format, our model simply holds the raw format of the data. Our View contains the formatted date and our ViewModel acts as a middle-man between the two.

KnockoutJS interprets the ViewModel as the represtation of data and operations that can be performed on a UI. 

Another simple example with code.

The intent of Knockout and other MVVM framework offerings is to move those conditional logic statements into the ViewModel and let the ViewModel be the sole source of the business logic



July 18, 2012 Posted by | Uncategorized | , | Leave a comment