KnockoutJS provides the following control statements:
- foreach
- if
- ifnot
- with
The following explains each one of the bindings.
The foreach bindings
The "foreach" binding renders the specific section of HTML markup repeatedly for the each item of a specified array. The following is the syntax and parameters for the foreach binding.
<b>foreach binding </b>
<ul
data-bind="foreach:
{ data: people, as:
'person',
includeDestroyed:
true,
afterRender: yellowFadeIn }">
<li
data-bind="text:
person.name"></li>
</ul>
<a
class="link"
data-bind="click:
addPerson">Add
Item</a>
In the preceding markup, we have
the foreach binding associated with the ul element. We will see the options
passed as an object with the foreach binding. KnockoutJS renders the li element
repeatedly depending on the observable array items. Each item will be bound with
the respective li element.
- data - Should be a collection, in other wods an array or observable array.
- as - Refers to the current item of the array or observable array. The value assigned to 'as' should be a string literal.
- includeDestroyed - Should be true or false. If it is true then the deleted item will be removed from the rendered markup but not from the collection bound.
- afterRender/afterAdd/beforeRemove/beforeMove/afterMove - Should be a callback function and will be executed corresondingly.
In our foreach binding example, if you click on the "Add Item" link then an item will be added into the observableArray and the same will be rendered on the HTML page. Since we have a "afterRender" callback bound with the ul element, the callback will be executed after the render.
The if binding
The "if" binding adds/removes the associated element based on the value/expression assigned to the binding. If the value is true or true-ish, then the element will be added to the parent node else removed from the DOM.
<b>if binding</b>
<p> <inputtype="checkbox"data-bind="checked: isChecked"/>Check/Uncheck the checkbox to add/remove Hello node </p>

Join the conversation! Your thoughts help the community grow.