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

Special addressing forms


In the Knockout.js library, there are some specific keywords you will use. Let's review their Knockout MVC analogue:

  • $parent, $parents, $root, and $parentContext: These properties allow you to refer to different data binding contexts. You don't need think about the scopes hierarchy and peculiarities of addressing between them in Knockout MVC—now every context has a name! Consider the following code snippet:

    Razor: @using (var items = ko.Foreach(m => m.Items))
           {
             using (var subItems = items.Foreach(m => m.SubItems))
             {
               @subItems.Html.Span(m => ko.Model.Key + " " + items.Model.Caption + " " + m.Name)<br />
             }
           }
    Html:  <!-- ko foreach: Items -->
             <!-- ko foreach: SubItems -->
               <span data-bind="text : $parents[1].Key()+' '+$parent.Caption()+' '+Name()"></span><br />
             <!-- /ko -->
           <!-- /ko -->
  • $index: This makes it possible to get an index of a collection element in the Foreach context. You can use the GetIndex() function to get the corresponding property of each context:

    Razor: @using (var items = ko.Foreach(m => m.Items))
           {    
             <span @items.Bind.Text(items.GetIndex())></span>      
           }
    Html:  <!-- ko foreach: Items -->
             <span data-bind="text : $index()"></span>
           <!-- /ko -->
  • $data: This makes it possible to get a collection element in the Foreach context. In the Knockout MVC, you just should create a lambda expression that will map a model to itself, as shown here:

    Razor: @using (var items = ko.Foreach(m => m.Items))
           {    
             <span @items.Bind.Text(m => m)></span>      
           }
    Html:  <!-- ko foreach: Items -->
             <span data-bind="text : $data()"></span>
           <!-- /ko -->