Saturday, 5 October 2013

Knockout.js Simplified

Knockout is a fantastic JS library for data binding and dynamically generating complex HTML. It helps a lot in developing applications which are loosely coupled and where there is minimum dependency between the data and the views.

Before I knew knockout, I used to generate all my repetitive HTML right from my JavaScript file. This had significant disadvantages:
1) Every time I had to change my display code, I had to modify the JavaScript file.
2) The JavaScript file contained the business logic as well as the display logic of my application. This used to make the file very complicated to maintain.
3) If a UI designer had to change the HTML, he would have to consult me in order to look for where to make the changes so that the generated HTML would be according to his requirements.

With knockout, we can keep all the display logic (HTML) in the .html file while all the data logic (and business logic) can be separated in the JavaScript file.

Knockout JS implements the MVVM pattern for developing applications. Now if you are a beginner, all these acronyms like MVC/MVP/MVVM might get confusing. So let me try to explain what exactly is meant by the MVVM pattern.

MVVM stands for Model-View-ViewModel. I know this does not help you at all so let me go in a bit of detail:

Model : Your data. Typically a JSON or XML object which contains data fetched from different data sources like Web Services, SQL Tables, SharePoint Lists etc.

ViewModel: The component which aggregates the data into a format which the View expects. ViewModel also manages combining data from multiple Models. It also handles formatting, sorting, filtering of the data based on custom business logic.

View: HTML Structure which will display data to the user.

Hope that was helpful.

Now lets get into the code right away! We will be looking into a simple example where we will be getting data from an JavaScript Array (Model), filling that data into a ViewModel and then binding that ViewModel to the View (HTML).

Since this article is just introduction to KnockoutJS, I have kept it really simple. I have included the JS code as well as the HTML code in the same file so that it is easier to understand. You will want to separate out the JS code in a different file.

Here is the code:



For more details and tutorials, please see the Knockout.JS documentation which is really nice and detailed: http://knockoutjs.com/documentation/introduction.html