Book Image

Getting Started with Knockout.js for .NET Developers

By : Andrey Ankshin
Book Image

Getting Started with Knockout.js for .NET Developers

By: Andrey Ankshin

Overview of this book

Table of Contents (14 chapters)
Getting Started with Knockout.js for .NET Developers
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 => m.SubSubModel))
             {
               @subSubModel.Html.Span(m => ko.Model.ModelName + " " + subModel.Model.SubModelName + " " + m.SubSubModelName)
             }
           }
    Html:  <!-- ko with: SubModel -->
             <!-- ko with: SubSubModel -->
               <span data-bind="text : $parents[1].ModelName()+' '+$parent.SubModelName()+' '+SubSubModelName()"></span>
             <!-- /ko -->
           <!-- /ko -->
  • If: With this, some elements will be displayed according to a specified condition:

    Razor: @using (ko.If(model => model.Condition1 || model.Condition2))
           {
             <p>Text</p>
           }
    Html:  <!-- ko if: Condition1()||Condition2() -->
             <p>Text</p>
           <!-- /ko -->