Introduction to Knockout.JS - Part Four

Before reading this article, I highly recommend reading the previous part of the series on Knockout.JS,

Now we are going to understand binding contexts with special properties and control flow statements.

  1. $Data: View Model object in the current context
  2. $Index: Zero based Index of the current array entry being rendered by a foreach binding. It is automatically updated fromthe observable array.
  3. $ParentContext: Binding context at the parent level.

Control Flow Statement

Foreach:

Step 1: Create one project in VS 2013. I am going to create MVC empty application.

  1. public ActionResult Array()  
  2. {  
  3.    return View();  
  4. }  
Add action method and view for same action method. By right clicking on project add KnockOut.js & JavaScript files from Manage Nuget packages. Add knockout.js & JavaScript reference to our view.

Step 2:
The foreach binding adds a markup for each entry in an array, and binds each copy of that markup to the corresponding array item and shows that values using data-bind. Array elements are automatically print using foreach.

Step 3: I have created view as follows which contains the example of binding view model objects using $Data in current context.
  1. @{  
  2. Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>Example of foreach using $Data</title>  
  10.         <script src="~/Scripts/jquery-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout-3.4.0.js"></script>  
  12.         <script>  
  13.             $(document).ready(function () {  
  14.                 function salaryViewModel() {  
  15.                     var empSalary = this;  
  16.                     empSalary.items = ['25000''20000''150000'];  
  17.                 }  
  18.                 ko.applyBindings(new salaryViewModel());  
  19.             })  
  20.         </script>  
  21.     </head>  
  22.     <body>  
  23.         <div>  
  24.             <h4 style="color:brown">Example of foreach using $Data</h4>  
  25.             <ul data-bind="foreach: items">  
  26.                 <li>The value is   
  27.                     <span data-bind="text: $data"></span>  
  28.                 </li>  
  29.             </ul>  
  30.         </div>  
  31.     </body>  
  32. </html>  
Step 4: Now run our application,

array

Example of Binding context using $index properties

Step 1: I am going to create another action method and create a new view for the same action method.
  1. public ActionResult UsingIndexProperty()  
  2. {  
  3.    return View();  
  4. }  
Here array elements automatically increment using index with the help of foreach they are rendered on our view.
  1. @{  
  2. Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>Binding Context using $index</title>  
  10.         <script src="~/Scripts/jquery-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout-3.4.0.js"></script>  
  12.         <script>  
  13.             $(document).ready(function () {  
  14.                 function DataViewModel() {  
  15.                     this.myNumbers = ko.observable(5);  
  16.                 }  
  17.                 ko.applyBindings(new DataViewModel());  
  18.             })  
  19.         </script>  
  20.     </head>  
  21.     <body>  
  22.         <div>  
  23.             <h4 style="color:darkmagenta">Example of Binding Context using $index Property</h4>  
  24.             <ul data-bind="foreach: new Array(myNumbers())">  
  25.                 <li data-bind='text: $index()+1000'></li>  
  26.             </ul>  
  27.         </div>  
  28.     </body>  
  29. </html>  
Step 2: Now run our application and we will see output as:

Now run our application

If:

If binding causes a section of markup to appear in View using data-bind whenever if condition evaluates to true if condition is same as visible binding (we had discussed in my Introduction To Knockout.JS - Part 2).

Step 1: I am going to create another action method & create new view for the same action method.
  1. public ActionResult if_Condition()  
  2. {  
  3.    return View();  
  4. }  
In our view take one button and use data-bind for click event. In another div take if condition in data-bind if value evaluates as true then this will show some text.

Step 2: Add the following code to our view:
  1. @{  
  2. Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>if condition</title>  
  10.         <script src="~/Scripts/jquery-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout-3.4.0.js"></script>  
  12.         <script>  
  13.             $(document).ready(function () {  
  14.                 ko.applyBindings({  
  15.                     myValue: ko.observable(false)  
  16.                 });  
  17.             });  
  18.         </script>  
  19.     </head>  
  20.     <body>  
  21.         <h4>Example of If condition</h4>  
  22.         <button data-bind="click:myValue"> My Value </button>  
  23.         <div data-bind="if: myValue">  
  24.             <br />Welcome to if condition.  
  25.         </div>  
  26.     </body>  
  27. </html>  
Step 3: Now run our application. For the first time it will not show the text.

 run application
Whenever we click on button if condition evaluates to TRUE and this will show text message.

click on button if condition
Ifnot:

If not, binding causes a section of markup to disappear in View using data-bind of if not condition.

Step 1: I am going to create another action method & creating new view for the same action method.
  1. public ActionResult Not_if()  
  2. {  
  3.    return View();  
  4. }  
In our view take one checkbox and use data-bind for checing event. In another div take if not condition in data-bind.

Step 2: Add the following code to our view:
  1. @{  
  2. Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>ifnot condition</title>  
  10.         <script src="~/Scripts/jquery-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout-3.4.0.js"></script>  
  12.         <script>  
  13.             $(document).ready(function () {  
  14.                 ko.applyBindings({  
  15.                     myValue: ko.observable(false)  
  16.                 });  
  17.             });  
  18.         </script>  
  19.     </head>  
  20.     <body>  
  21.         <h4>Example of Ifnot condition</h4>  
  22.         <label>  
  23.             <input type="checkbox" data-bind="checked: myValue" /> click in checkbox to hide bellow text  
  24.         </label>  
  25.         <div data-bind="ifnot: myValue">  
  26.             <br /> Welcome to ifnot condition.  
  27.         </div>  
  28.     </body>  
  29. </html>  
Step 3: Now run our application. For the first time it will show the text.

run our application

Whenever we click checkbox, the text will disappear as:

click in checkbox

Another example of foreach condition

Step 1: Create another action & view for same action method.
  1. public ActionResult ForeachLoop()  
  2. {  
  3.    return View();  
  4. }  
Add the following code to our view:
  1. @{  
  2. Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6. <html>  
  7.     <head>  
  8.         <meta name="viewport" content="width=device-width" />  
  9.         <title>Initialize an Array </title>  
  10.         <script src="~/Scripts/jquery-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout-3.4.0.js"></script>  
  12.         <script>  
  13.             $(document).ready(function () {  
  14.                ko.applyBindings({  
  15.                   bookDetails: [  
  16.                      { bookName: 'WCF', author: 'Vithal W.' },  
  17.                      { bookName: 'AngularJs', author: 'Jeetendra G.' },  
  18.                      { bookName: 'MVC', author: 'Rupesh K.' }  
  19.                   ]  
  20.                });  
  21.             })  
  22.          </script>  
  23.     </head>  
  24.     <body>  
  25.         <div>  
  26.             <h4 style="color:deepskyblue">Foreach loop example</h4>  
  27.             <table>  
  28.                 <thead>  
  29.                     <tr style="color:red">  
  30.                         <th>Book Name</th>  
  31.                         <th>Author Name</th>  
  32.                     </tr>  
  33.                 </thead>  
  34.                 <tbody data-bind="foreach: bookDetails">  
  35.                     <tr>  
  36.                         <td data-bind="text: bookName"></td>  
  37.                         <td data-bind="text: author"></td>  
  38.                     </tr>  
  39.                 </tbody>  
  40.             </table>  
  41.         </div>  
  42.     </body>  
  43. </html>  
This example shows iterating over an array.

Now run our application and see the output:

Run

Summary

This article will help fresher candidates to understand KnockOut.Js.
 
Read more articles on Knockout.JS:

 

Up Next
    Ebook Download
    View all
    Learn
    View all