Nested contexts

Nested contexts allow developers to wrap a part of a view in a special construction, which offers some additional behavior.

It is possible to create the following types of nested contexts:

  • Foreach: This nested context walks through all collection elements and provides easy access to HTML elements:
    Razor: @using (var items = ko.Foreach(m => m.Items))
           {
             <tr>
               <td @items.Bind.Text(items.GetIndex())>
               </td>
               <td @items.Bind.Text(m => m)>
               </td>
             </tr>
           }
    Html:  <!-- ko foreach: Items -->
             <tr>
               <td data-bind="text : $index()">
               </td>
               <td data-bind="text : $data">
               </td>
             </tr>
           <!-- /ko -->
  • With: This allows easy referring to a subentity of the main model:
    Razor: @using (var subModel = ko.With(m => m.SubModel)) { using (var subSubModel = subModel.With(m ...

Get Getting Started with Knockout.js for .NET Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.