Bindings in knockout Part 2

Rama Sagar
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 2353 red flag

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates.For more info


This article explains how to use control flow bindings in Knockoutjs

Knockoutjs provides the following control flow bindings

  • foreach
  • if
  • ifnot
  • with
 These control-flow bindings give you complete control over how your ViewModel is displayed in a view.

The foreach binding

<tbody data-bind='foreach: Students'>
    <td data-bind='text: Firstname'></td>
    <td data-bind='text: Lastname'></td>
    <td><button data-bind='click: $root.removeStudent'>Remove</button></td>
When Knockout.js encounters foreach in the data-bind attribute, it iterates through the Students array and uses each item it finds for the binding context of the contained markup. This binding context is how Knockout.js manages the scope of loops. 

The if binding

The if binding is a conditional binding. If the parameter we pass evaluates to true, the contained HTML will be displayed, otherwise it’s removed from the DOM. For Example if the checkbox is checked we are showing the message
<label><input type="checkbox" data-bind="checked: displayMessage" /> Display message</label>
<div data-bind="if: displayMessage">Welcome to </div>
The ifnot binding

The ifnot binding is exactly the same as the if binding, except that it inverts the result of whatever expression we pass to it
<div data-bind="ifnot: someProperty">...</div>
The with binding

The with binding can be used to manually declare the scope of a particular block. 

<h1 data-bind="text: city"> </h1>
<p data-bind="with: location">
    Latitude: <span data-bind="text: latitude"> </span>,
    Longitude: <span data-bind="text: longitude"> </span>


In this article we have learned how to use control flow bindings in Knockoutjs


Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)