Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout, nested foreach

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 -->
like image 916
Ilya Avatar asked Jul 30 '12 12:07

Ilya


People also ask

For what purpose do we use foreach binding in 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.

What is $data in knockout?

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.

What is Ko observable?

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.

How do you bind data in an array?

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.


2 Answers

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.

like image 157
Kyeotic Avatar answered Oct 11 '22 15:10

Kyeotic


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 -->
like image 21
Jibi Abraham Avatar answered Oct 11 '22 16:10

Jibi Abraham