Why Knockout ?

When I worked for a single pager cross platform mobile application, there were lot of UI need to be updated very frequently, Initially I did that using Jquery which is an awesome js library, but still I need to write lots of code to find and update the element every time there is a change in the UI.

So I was looking out for some JavaScript libraries to simplify my work and came through Knockout js library, which is a dynamic JavaScript library using MVVM pattern.

No Other JS Library Dependencies

It has dynamic bindings, automatic ui refresh, dependency tracking and templating. The good thing is that it is not dependent on any JavaScript libraries like jQuery or Prototype. Just knockout.js library is enough in your app.

They have a very good interactive tutorial on their website which can help you to get started quickly. You can try it out at Knockout Tutorial.

External Templating Engines

Knockout has bindings for almost all the elements with text, values and events as well. Templating is also available.
I am a big fan of Underscore.js and Knockout also allows us to integrate some external string based templating engine like Jquery template and underscore templating engine.

Simple Code Snippet

<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<div>Name: <span>Samsumg Grand</span></div>
<div>Price:<span>22,000</span></div>

Step 1 : add “data-bind” attribute

<div>Name: <span data-bind="text : product_name">Samsumg Grand</span></div>
<div>Price:<span data-bind="text : product_price">22,000</span></div>

Step 2 : apply bindings

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function updateValues() {
    this.product_name= "Apple iPhone 4s";
    this.product_price= "35,000";
}

// Activates knockout.js
ko.applyBindings(new updateValues());
</pre>

Output :

Name: Apple iPhone 4s
Price: 35,000

I am almost done with one of my one pager mobile application with Knockout js, will share more about my experience with knockoutjs and code samples in my next blog.

Advertisements