Create Your First MVVM Based JavaScript App in Three Simple Steps Using Knockoutjs

Create your first MVVM based JavaScript App in two simple steps using Knockoutjs.

Okay, the purpose of this article is to provide a very simple explanation of why to use Knockoutjs. I will try to put it in the simplest way possible of why we need to use Knockoutjs.  If you are not a beginner then probably this article may appear very simple to you. However I request that you contnue reading this article.  

Without Knockoutjs

Let us start with an application as given below. The application has two input boxes and a span to display a message.

start with an application

The requirement of this application is as follows:

  1. Pull data from a data source. In this scenario the data source is a plain JavaScript object.
  2. Create a custom message.
  3. Display the message in a label.
  4. Notify the data source when the data in the input boxes change.

Let us do it using jQuery and without Knockoutjs.  The view above is simple to create as in the following:

<h1>KO Demo</h1>   

     <span id="spnProductName">Product Name</span> <input type="text" id="txtProductName" />

     <span id="spnProductPrice">Product Price</span><input type="text" id="txtProductPrice" /><br />

  <h2> <span id="spnMessage"></span> </h2>
 
A datasource can be created as a plain JavaScript object. This can be created as in the following:
 
  
 var Product =
        {
            productName"Pen",
            productPrice: 200
        };


 Next we need to bind this data to input box elements of the DOM. This can be done using jQuery selectors. We need to select elements and assign values to elements.
 
 
$("#txtProductName").val(Product.productName);
 $("#txtProductPrice").val(Product.productPrice);
 var message = Product.productName + " costs " + Product.productPrice;
$("#spnMessage").text(message);

 
In the code snippet above we are creating a custom message, reading values from the JavaScript object and then assigning that to a span element on the DOM.

This is all that we need to do. When you run the application you should get the elements repopulated with data from the JavaScript object.

custom message from JavaScript object

One major problem in the implementation above is that if you change the Product Name or Product Price then it will not notify the data source. Here you are pulling data from the data source and there is no binding between the elements and the data source.

In simple words, when you change the value of the Product Name or Product Price, the custom message will not change by default. Of course you can implement it using jQuery but that would be complex.
 
With Knockoutjs
 
Now let us implement the preceding requirements using Knockoutjs. In Ko we need to create:

  1. Model
  2. ViewModel
  3. View

In this requirement we will create only a ViewModel and View.

Step 1: Creating View

A View is nothing but HTML elements. So we can reuse the view used in the example above. But we need to use a data-bind attribute of HTML5 to bind data from a data source.  For example, if you want to display (bind) a Product Name to the first input box. To do this we will bind the value attribute to productName (this is the property representing the Product Name in the ViewModel).

Creating View
 
We can create a complete View of the application
as in the following:

    <h1>With KO</h1>

     <span id="spnProductNamek">Product Name</span> 

    <input type="text" 

          id="txtProductNamek" 

           data-bind="value:productName" />

 

     <span id="spnProductPricek">Product Price</span>

    <input type="text" id="txtProductPricek" 

        data-bind="value : productPrice" />

    <br />

    <h2> <span id="spnMessagek" data-bind="text:message"></span> </h2>


 
You can see in the View implementation that we are binding the Product Name, Product Price and Message to coresponding elements.

Step 2: Creating ViewModel
 
A ViewModel can be created as simple JavaScript Objects.  We need to keep in mind that, to enable Two Way Binding properties of an object it should be as a Knockout Observable. A ViewModel can be created as in the following:
 
 
var ProductViewModel =
  {
       productNameko.observable("Pen"),
       productPriceko.observable(200),
                 
   };

 
Next we need to create a Message property as a Computed Observable.  A Computed Observable can be created as in the following:

Creating ViewModel
 
To create a computed observable you need to pass a function and the name of the ViewModel. Note that there are various ways to create a ViewModel. For the purpose of this article we followed this approach to add a computed observable to a ViewModel.

As last step we need to apply binding or link a ViewModel to a Node on the DOM.  If you want to bind a ViewModel to an entire body then you can skip the second parameter.

ViewModel to a Node on DOM
 
Putting the preceding explanation together with the full source code to create an app using MVVM and KO is as follows:
 
   
var ProductViewModel =
    {
          productNameko.observable("Pen"),
          productPriceko.observable(200),
                 
      };

    ProductViewModel.messageko.computed(function () {
        var m = this.productName() +
                 " costs " +
                 this.productPrice();
        return m;
    }, ProductViewModel)

    ko.applyBindings(ProductViewModel)

 
Now let us proceed to run the application.

application Output
 
In the preceding application, when you change a value in any of the input boxes, the message in the label will be immediately changed. So we have seen that two way binding and automatic UI refresh is very simple to implement using Knockoutjs.