Let's I have Humans with Cats with Kittens
class Master
{
String masterName;
Cat[] cats;
}
class Cat
{
String catName;
Kitten[] kittens;
}
class Kitten
{
String kittenName;
}
Now I want show all my Kittens with Cats with Masters in html. I use
<!-- ko foreach: humans -->
<!-- ko foreach: cats -->
<!-- ko foreach: kittens -->
<p data-bind="$data.kittenName"></p>
<p data-bind="$parent.catName"></p>
<p data-bind="???????"></p> <!-- How get master's name? -->
<!-- /ko -->
<!-- /ko -->
<!-- /ko -->
Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
An observable is useful in various scenarios where we are displaying or editing multiple values and require repeated sections of the UI to appear and disappear as items are inserted and deleted. The main advantage of KO is that it updates our UI automatically when the view model changes.
If you want to access the array by index, you need to evaluate the observable first using () . If you want the value binding to work two-ways (i.e.: not only set it initially, but also update the values in your viewmodel after a change), you'll have to bind them to ko.
From the knockout documentation
$parents This is an array representing all of the parent view models:
$parents[0] is the view model from the parent context (i.e., it’s the same as $parent)
$parents[1] is the view model from the grandparent context
You should be able to use $parents[1]
to access the Master viewmodel.
You can use, $root
to get to the base object - which in your case will be at the level of Master
.
<!-- ko foreach: humans -->
<!-- ko foreach: cats -->
<!-- ko foreach: kittens -->
<p data-bind="$data.kittenName"></p>
<p data-bind="$parent.catName"></p>
<p data-bind="text:console.log($root, $parent, $data)"></p> <!-- How get master's name? -->
<!-- /ko -->
<!-- /ko -->
<!-- /ko -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With