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

Read all Knockoutjs posts here

Setting up Visual Studio 2013 for Knockoutjs Development

Okay purpose of this post is very simple to explain you why Knockoutjs. I will try to put it in simplest way that Why we need to work Knockoutjs. If you are not a begineer then probably this post may appear very simple to you. However I request keep reading this post.

Without Knockoutjs

Let us start with an application as given below. Application got two input box and a span to display a message.

image

Requirement of this application is as follows ,

  • Pull data from a data source. In this scenario data source is a plain JavaScript object.
  • Create a custom message.
  • Display message in label.
  • When data changes in input boxes notify back to data source.

Let us do it using jQuery and without Knockoutjs. Above view can be created simply as below,



 <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 plain JavaScript object. This can be created as below,


  var Product =
        {
            productName: "Pen",
            productPrice: 200
        };

Next we need to bind this data to input boxes element on 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 above code snippet we are creating a custom message reading values from JavaScript object and then assigning that to span element on DOM.

This is what all we need to do. When you run application you should get elements are prepopulated with data from JavaScript object.

clip_image001

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

In simple words when you change value of Product Name or Product Price custom message will not change by default. Off course you can implement it using jQuery but that would be complex.

With Knockoutjs

Now let us implement above requirement using Knockoutjs. In Ko we need to create

  • Model
  • ViewModel
  • View

In this requirement we will create only ViewModel and View.

Step 1: Creating View

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

image

We can create complete View of application as below,



<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 View implementation that we are binding Product Name, Product Price and Message to different elements.

Step 2: Creating ViewModel

A ViewModel can be created as a simple JavaScript Objects. We need to keep in mind that to enable Two Way Binding properties of object should be as Knockout Observable. ViewModel can be created as follows,


 var ProductViewModel =
      {
          productName: ko.observable("Pen"),
          productPrice: ko.observable(200),
                 
      };


Next we need to create Message property as Computed Observable. Computed Observable can be created follows,

image

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

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

image

Putting above discussion together and full source code to create app using MVVM and KO are as follows


   var ProductViewModel =
      {
          productName: ko.observable("Pen"),
          productPrice: ko.observable(200),
                 
      };

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

    ko.applyBindings(ProductViewModel)


Now let us go ahead and run application.

clip_image001[6]

In above application when you change value in any of the input boxes, immediately message in label will be changed.

So we witnessed that two way binding and automatic UI refresh is very simple to implement using Knockoutjs.  I hope you find this post useful. Thanks for reading.

6 responses to “Create your First MVVM based JavaScript App in two simple steps using Knockoutjs”

  1. […] up Visual Studio 2013 for Knockoutjs Development and Create your First MVVM based JavaScript App in two simple steps using Knockoutjs (Dhananjay […]

  2. […] Create your First MVVM based JavaScript App in two simple steps using Knockoutjs […]

  3. […] Create your First MVVM based JavaScript App in two simple steps using Knockoutjs […]

  4. […] Create your First MVVM based JavaScript App in two simple steps using Knockoutjs […]

Leave a comment

Create a website or blog at WordPress.com