Friday, April 4, 2014

Simple Knockout.js example in ASP.NET Webform

Intrigued with emerging Javascript framework called knockout, I decided to try a simple example myself.
As defined by Wikipedia:
Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore:
1. A clear separation between domain data, view components and data to be displayed
2. The presence of a clearly defined layer of specialized code to manage the relationships between the view components

The features of Knockout are based on Declarative bindings:
A. Automatic UI refresh (when the data model's state changes, the UI updates automatically)
B. Dependency tracking
C. Templating (using a native template engine although other templating engines can be used, such as jquery.tmpl)


I come to a conclusion that this has similar approach to WPF MVVM.

So, to get started with, download the latest Knockout.js framework here: Knockout Home Page and add reference to your html or aspx markup:
Code:
 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title>Simple Knockout JS</title>    
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <h2>My First KnockoutJS example</h2>  
   <div>  
     My name is: <span data-bind="text: personName"></span><br />  
     My Age is: <span data-bind="text: personAge"></span>  
   </div>  
   <script type="text/javascript" src="Scripts/knockout-3.1.0.js"> </script>  
   <script type="text/javascript">  
     var myViewModel = {  
       personName: 'PsychoGenes',  
       personAge: 33  
     };  
     ko.applyBindings(myViewModel);  
   </script>  
   </form>  
 </body>  
 </html>  
Running aspx page:

Cheers! :)

0 comments:

Post a Comment