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 theForeach
context. You can use theGetIndex()
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 theForeach
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 -->