Implementing MVVM Pattern using Knockout

Implementing MVVM Pattern using Knockout

Introduction to MVVM
MVVM (Model View ViewModel) is an architectural pattern which separates the user-interfaces (UI) development from business logic and behavior in an application.
The basic three components of MVVM are:
1. Model: Model in MVVM represents information that our application will be working with. A typical example might be a user account(FirstName,LastName,MobileNo,EmailId)
2. View: The view is the application’s User Interface (UI). It defines the appearance of the UI and its controls such as text boxes and buttons.
3. ViewModel: View Model refers to data and UI level operations that we wish to perform on the data.


Introduction to Knockout

Knockout is a free,small, lightweight and open source JavaScript library that helps us to develop rich data driven web user interfaces using MVVM pattern.

Headline features:

  • Elegant dependency tracking – automatically updates the right parts of UI whenever data model changes.
  • Declarative bindings – a simple and obvious way to connect parts of UI to data model. We can construct complex dynamic UIs using arbitrarily nested binding contexts easily.
  • Trivially extensible – implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.

To create a View Model with Knockout, declare JavaScript object as below:
var PersonViewModel = {
personName: ‘XYZ’,
personAge: 20

To create a simple View of this view model use below code:
The name is <span data-bind=”text: personName”></span>


One of the most important key benefits of KO is that it updates UI automatically when the view model changes using observables which are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.

For example, rewrite the preceding view model object as follows:
var PersonViewModel = {
personName: ko.observable(‘XYZ’),
personAge: ko.observable(123)

Now no need to change the view,the same data-bind syntax will work.The only difference is that it is now capable of detecting changes and updates view automatically.

Activating Knockout: The data-bind attribute isn’t known to HTML But since the browser doesn’t know what it means, we need to activate Knockout by adding the following line to a <script> block:

CONCLUSION: Knockout allows us to develop data driven rich UI easily using MVVM design pattern which automatically tracks changes to the data, helping us to synchronize the View and the View Model.

  • Implementing MVVM,
  • Implementing MVVM Pattern,
  • Implementing MVVM Pattern using Knockout,
  • Knockout,
  • MVVM,
  • Leave a Reply