javascript 淘汰赛,嵌套foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11721270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
knockout, nested foreach
提问by Ilya
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
现在我想用 html 显示我所有的小猫和主人的猫。我用
<!-- 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 -->
回答by Kyeotic
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
$parents 这是一个代表所有父视图模型的数组:
$parents[0] 是来自父上下文的视图模型(即,它与 $parent 相同)
$parents[1] 是祖父母上下文中的视图模型
You should be able to use $parents[1]
to access the Master viewmodel.
您应该能够使用$parents[1]
来访问主视图模型。
回答by Jibi Abraham
You can use, $root
to get to the base object - which in your case will be at the level of Master
.
您可以使用,$root
访问基础对象 - 在您的情况下,它将处于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 -->