Control Flow Bindings in Knockout.js

You can control the flow of an element on the view using Control Flow bindings of Knockout.js. There are the following four Control Flow bindings:

  1. foreach binding
  2. if binding
  3. ifnot binding
  4. with binding

Out of these four bindings foreach and if bindings are used very often.

foreach binding
 
A foreach binding repeats the same markup once for for each element in an array. It also binds each repeat of mark-up to the corresponding item of the array. 

foreach binding
Let us try to understand it with an example. Assume we have a ViewModel that contains an observable array as one of the observables.

var viewModel =
{
    studentsko.observableArray
        ([
            {name :"Dan W"subject : "JavaScript" },
            { name"Glenn B"subject"Node" },
            { name"Pinal D"subject"SQL" }
       ])
}

 
ViewModel contains a property, students, that is an observable array. We can bind this on the view to a table or list elements.

<table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Subject</th>
            </tr>
        </thead>
        <tbody data-bind="foreachstudents">
            <tr>
                <td data-bind="textname"></td>
                <td data-bind="textsubject"></td>
            </tr>
        </tbody>
    </table>

As youcan see, on the table body we are performing foreach binding. So the mark-up inside the table body would be repeated 3 times in this case, since the number of elements in the observable array is 3.

On running this application you will get the table rendered with three rows as below:

observable array
 Next let us consider one complex scenario in which we want to add and remove students. So let us proceed to an update view model with a computed observable to add and remove items from an observable array.

function viewModel()
        {
        var self=this;
        self.studentsko.observableArray
              ([
                  {name :"Dan W"subject : "JavaScript" },
                  { name"Glenn B"subject"Node" },
                  { name"Pinal D"subject"SQL" }
              ]);
        self.addStudentfunction ()
        {
            self.students.push({ name"dj"subject"JavaScript" });
        };
         self.removeStudentfunction ()
            {
                self.students.remove(this);
            }
        }
    ko.applyBindings(new viewModel());

There is nothing very fancy in the above ViewModel. We just add computed observables to add and remove students. Next we can bind that to a view containing an unordered list as below:

<h4>Students</h4>
    <ul data-bind="foreachstudents">
        <li>Name at position <span data-bind="text$index"></span>:
        <span data-bind="textname"></span>
            <a href="#" data-bind="click$parent.removeStudent">Remove</a>
        </li>
    </ul>
 <button data-bind="clickaddStudent">Add</button>

 
On running the application you will find that now you can add and remove students.

add and remove items from observable array
You can use $index, $parent and $data with foreach binding as well. For example:

  • You can read index of a specific element using   $index.
  • You can read array element using $data. Not a specific element
  • You can read parent viewmodel or other properties of viewmodel using $parent

if binding

if binding determines whether a section of mark-up will appear or not. Unlikely visible binding if binding adds or removes markup from the DOM. It performs the following tasks:

  • Add or remove markup from the DOM
  • Ensure that the data-bind attribute has applied to the markup

Now let us see if binding in action. Let us say you have a ViewModel as below:

var viewModel =
{
    show : ko.observable(false)
}
ko.applyBindings(viewModel);

 
On the View we can do binding as follows:
 
<label><input type="checkbox" data-bind="checkedshow" />Display Div</label> 
      <div data-bind="ifshow">Visible/Hide using if binding  </div>

 
You can see that we are doing checked binding on input checkbox whereas performing if binding on the div. If the value of the ViewModel property evaluates to a non-false value then the div would be visible. Input is toggling the value of the show property. Let us take another example in which we will learn how if binding is useful when working with nulls. As you know, if binding adds or removes elements on the DOM having their data binding applied on that. Consider the following ViewModel:

function viewModel() {
var self = this;
self.students = ko.observableArray
     ([
          { name"Dan W"subjectnull },
           { name"Glenn B"subject: { music'guitar' } },
            { name"Pinal D"subject: { music'drum' } }
      ]);
};
 

Next we need to do if binding on the view as in the following:

<h4>Students</h4>
    <ul data-bind="foreachstudents">
    <li>
        Student: <b data-bind="textname"> </b>
        <div data-bind="ifsubject">
            Subject: <b data-bind="textsubject.music"> </b>
        </div>
    </li>
</ul>

 
You see above that we are applying if binding on the div to display the subject. If binding adds or removes on the basis of non-falsie values. So for the student, the subject value is set to null; this div will not be created. If you try to do it using visible binding then for any student for which the value of subject is set to null, you will get a subject.music throwing an exception.
 
Ifnot  binding
 
This is exactly the same as if binding, it only inverts  the value passed to it.

So let us say you have a ViewModel as below:
 
 var viewModel =
        {
            display : ko.observable(false)
        }

        
And you  bind this to a view as given below:
 
<div data-bind="ifnotdisplay">
     <h1>hello</h1>
</div>

 
Then when running you will find the div is added to the DOM even though the display property in the ViewModel is set to false. Because ifnot binding inverts the value of the property in the ViewModel.

When you create a MVVM application using Knockout.js, control flow binding is very useful. You will use it very often and I hope you find this article useful in understanding control flow binding. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all