Friday, June 6, 2014

KnockoutJS

Knockout js for Beginners


Introduction: 

Knockout js (shortly called KO) is a very popular JavaScript library and increasing its popularity day by day. This library helps to create rich/responsive/interactive web applications. It works directly with the web application's underlying data model. Using KO with any web application is very simple, clean, and straightforward, it is very powerful in the context of dynamic UI creation.  

Background 

JavaScript plays a very important role for developing today's modern web applications. Once upon a time, we just wrote a few JavaScript lines for data validation from the client side. But day by day JavaScript plays a vital role not only in data validation but also for creating responsive, robust web UI. For that reason, day by day a new JavaScript framework/library comes into market. We as smart developers, must adopt them and try to use them with our applications.  

Benefits   

If we use KO with web applications, we can get following benefits 
  • Anytime we can connect UI elements with data model. 
  • Easily create complex dynamic data model.  
  • Automatically update UI when Data Model is changed, when UI is changed then Data Model is changed automatically.  
  • Support event-driven programming model.  
  • Extend custom behavior very easily. 
  • All main-stream browsers are supported (IE, FireFox, Crome, Safari)   


Knockout with MVVM

  What is MVVM? Well, The full form of MVVM is Model View ViewModel. It is an architectural design pattern origined by Microsoft and mainly created for WPF/Silverlight applications. But we can use this Web application too with ASP.NET.   

MVVM is a specific implementation targeted at UI development platform which support event driven programming for WPF/Silverlight. It respect the programming principle "Separation of Concern". It completely separate GUI Rendering logic from Application Logic (Data Logic/Business Logic).   
KO built on that architectural design pattern. So if you want to understand KO properly then you should know about MVVM first.  


MVVM Overview   

The following diagram will show the style of MVVM 


MVVM has 3 parts:
  1. Model 
  2. View    
  3. ViewModel    
  • Model: Responsible for holding Application data. When  User enter data with UI elements, That data will store to a Model. So we can thinks like it is data part of the pattern.
  • View:  Responsible for presenting model data to the user. User elements are the part of the View. It provide structure/Layout of the User Interface and present to the user.
  • ViewModel: Connector of Model and View. Main responsibility is establish communication with View and Model. It hold data and function. Functions manipulate that data and it reflect to the UI. When data changed, UI is changed, when UI changed data is changed. ViewModel will does it for us with the help of databinding concept. 

MVVM Benefits
`````````````````````
Main benefits of MVVM:
  • Provide more flexibility  of designer and developer works.
  • Thorough unit testing 
  • Provide flexibility to change user interface without having to re-factor other logic of the codebase.
  • Provide more re-usability of UI component.   

Include KO library to Web Application
`````````````````````````````````````````````````
CDN (Content Delivery Network) reference of Knockout js is available at Microsoft CDN repository. There are two versions available. One for compact (minified) another for debug. It is recommended to use minified version. The url are
If your application is ASP.NET WebForm then you can download js file from above locations and store it to your web folder/subfolder and reference it to your page/master page.


<script src="~/Scripts/knockout-2.2.1.js" type="text/javascript"></script>
CDN Reference:
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js" type="text/javascript"></script>  
 If ASP.NET MVC application you can take reference inside @section  
@section scripts {
    <script src="~/Scripts/knockout-2.2.1.js"></script>
}
CDN Reference: 
@section scripts {
    <script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
} 


Example-1
``````````````
I will create a simple Employee information entry form. Form will accept some basic employee related data from the user and submit that data to the MVC Action with the help of AJAX. In View part , I will use various html element so that I can show how all elements are worked with KO. 

Implementation: 
Before start showing  code with KO just mention one thing. In MVVM pattern, a personal choice is there. That is which come first, Model Or View. I am not going to discuss detail on that. Just mention my personal preference and that is View. I always like to start View first then for Model. 
<form id="employeeForm" name="employeeForm" method="POST">
    <div id="form-root">
        <div>
            <label class="form-label">First Name:</label>
            <input type="text" id="txtFirstName" 
              name="txtFirstName" data-bind="value:Employee.FirstName" />
        </div>
         <div>
            <label class="form-label">Last Name:</label>
            <input type="text" id="txtLastName" 
              name="txtLastName" data-bind="value:Employee.LastName"  />
        </div>
        <div>
            <label class="form-label">Full Name:</label>
            <input type="text" id="txtFullName" name="txtFullName" 
              data-bind="value:Employee.FullName" readonly="readonly"  />
        </div>
        <div>
            <label class="form-label">Date Of Birth:</label>
            <input type="text" id="txtDateOfBirth" 
              name="dateOfBirth" data-bind="value:Employee.DateOfBirth"  />
        </div>
        <div>
            <label>Education:</label>
            <input type="checkbox" value="graduation" id="chkGraduation" 
              name="chkGraduation" data-bind="checked:Employee.EducationList" />Graduation
            <input type="checkbox" value="postGraduation" 
              id="chkPostGraduation" name="chkPostGraduation" 
              data-bind="checked:Employee.EducationList" />PostGraduation
        </div>
        <div>
            <label>Gender:</label>
            <input type="radio" id="rdoMale" name="gender" 
              value="0"  data-bind="checked:Employee.Gender" />Male
            <input type="radio" id="rdoFeMale" name="gender" 
              value="1" data-bind="checked:Employee.Gender"  />FeMale
        </div>
        <div>
            <label class="form-label">Department:</label>
            <select id="ddlDepartment" name="ddlDepartment" 
              data-bind="options:$root.Employee.DepartmentList, optionsValue:'Id', 
                optionsText:'Name', value:Employee.DepartmentId">
            </select>
        </div>
        <div>
            <input type="button" id="btnSubmit" 
              value="Submit" data-bind = "click: submit" />
             <input type="button" id="btnReset" 
               value="Reset" data-bind = "click: reset" />
        </div>
    </div>
</form>

No comments:

Post a Comment