Skip to content

Knockout 2.0 is here

22 December 2011

A Christmas release of Knockout has been published.

For those missed this library this is a great Javascript binding library applying Model-View-View-Model (MVVM) pattern. It is ideal for dynamically updated sections of any Web page.

So what about version 2.0

1. New control flow bindings

if, ifnot, with, and foreach control flow bindings. As usually easy to apply:

<em data-bind="if: student">
  &mdash; made by <span data-bind="text: student.name"></span>
</em>

This allows conditional data flow without any template.

The “with” binding changes the binding context to whatever object you specify which makes it easy to compose many independent view models together.

<div data-bind="with: class">
    <h3>Class</h3>
    <table>
        <thead><tr><th>Name</th><th>Grade</th></tr></thead>
        <tbody data-bind="foreach: student">
            <tr>
                <td data-bind="text: name"></td>
                <td data-bind="text: grade"></td>                
            </tr>
        </tbody>
    </table>
</div>

2. New comment-based control flow syntax

This allows to set up template-less control flow but without extra container elements. This means string-based templates could be skipped and binding-based control flows could be used instead.

<h3>Students</h3>
<ul>
    <li><strong>Here is a static contents</strong></li>
    <!-- ko foreach: students -->
    <li>
        <em data-bind="text: name"></em>
        <!-- ko if: student -->        
            &mdash; made by <span data-bind="text: student.name"></span>
        <!-- /ko -->
    </li>
    <!-- /ko -->
</ul>

3. Access to parent

When using nesting control flow there is necessary to reference parent binding properties. There are four new pseudo-variables created for that purpose:

  • $data – gets current item
  • $parent – gets parent item
  • $parents – an array with all parents. Smallest (zero) index is closest parent. Biggest  index (n-1) is the most outer level.
  • $root– gets top binding leve
<h3>Products</h3>
<ul data-bind="foreach: products">
    <li>
        <strong data-bind="text: name"></strong>
        &mdash;
        Last updated: <em data-bind="text: $parent.lastUpdated"></em>
    </li>
</ul>

Finally version 2.0 has improvements in event handling.

Interactive tutorials are available on the site. Also there are documentation and examples.

Advertisements

From → JavaScript

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: