2. 1. The foreach binding
2. The if binding
3. The ifnot binding
4. The with binding
5. The component binding
3. Purpose
• The foreach binding duplicates a section of markup for
each entry in an array, and binds each copy of that
markup to the corresponding array item. This is
especially useful for rendering lists or tables.
• Assuming your array is an observable array, whenever
you later add, remove, or re-order array entries, the
binding will efficiently update the UI to match -
inserting or removing more copies of the markup, or
re-ordering existing DOM elements, without affecting
any other DOM elements. This is far faster than
regenerating the entire foreach output after each array
change.
5. Purpose
• The if binding causes a section of markup to appear in your document
(and to have its data-bind attributes applied), only if a specified
expression evaluates to true (or a true-ish value such as a non-
null object or nonempty string).
Example
<label><input type="checkbox" data-bind="checked: displayMessage" />
Display message</label>
<div data-bind="if: displayMessage">Here is a message. Astonishing.</div>
<script type="text/javascript">
ko.applyBindings({
displayMessage: ko.observable(false)
});
</script>
6. Purpose
• The ifnot binding is exactly the same as the if binding, except that
it inverts the result of whatever expression you pass to it.
Example
<div data-bind="ifnot: someProperty">...</div>
...is equivalent to the following.
<div data-bind="if: !someProperty()">...</div>
The only reason to use ifnot instead of a negated if is just as a matter of
taste: many developers feel that it looks tidier.
7. Purpose
• The with binding creates a new binding context, so that
descendant elements are bound in the context of a
specified object.
Using “with” without a container element
<ul>
<li>Header element</li>
<!-- ko with: outboundFlight -->
...
<!-- /ko -->
</ul>
9. Purpose
• The style binding adds or removes one or more style values to
the associated DOM element. This is useful, for example, to
highlight some value in red if it becomes negative, or to set the
width of a bar to match a numerical value that changes.
Example
<div data-bind=“style: { color: currentProfit() < 0 ? 'red' : 'black' }“> Profit
Information </div>
<script type="text/javascript">
var viewModel = {
currentProfit : ko.observable(20000)
};
viewModel.currentProfit(-15);
</script>
10. Purpose
• The component binding injects a
specified component into an element, and optionally
passes parameters to it.
<a data-bind=“attr: { href: url, title: details}“> Report </a>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>