为简洁起见进行了更新
如何在嵌套的 Knockout foreach/with 绑定(bind)中引用 $parents 的 $parent?
例子-
<!-- ko foreach: grandParent -->
<tr>
<!-- ko foreach: $parent.parents --> // <-- Doesn't work
<!-- ko foreach: children -->
<td data-bind="if: favToy().name == $parent.$parent.favToy().name">
<span data-bind="text: favToy().name"></span>
</td>
<!-- /ko -->
<!-- /ko -->
</tr>
<!-- /ko -->
原创
很抱歉这个令人困惑的问题,但我正在尝试达到二级父值以检查当前上下文中的值(如下所示)以仅显示与 $parent 的 $parent 值匹配的跨度(呃!)
<!-- ko foreach: grandParent -->
<tr>
<!-- ko foreach: $parent.parents -->
<!-- ko foreach: children -->
<td data-bind="if: favToy().name == $parent.$parent.favToy().name">
<span data-bind="text: favToy().name"></span>
</td>
<!-- /ko -->
<!-- /ko -->
</tr>
<!-- /ko -->
这样做会更容易,但据我所知,这是不可能的,或者我做错了:)
<!-- ko foreach: grandParent -->
<tr>
<!-- ko foreach: $parent.parents -->
<!-- ko foreach: children ? favToy().name == $parent.$parent.favToy().name -->
<td data-bind="text: favToy().name"></td>
<!-- /ko -->
<!-- /ko -->
</tr>
<!-- /ko -->
如有任何帮助,我们将不胜感激。
最佳答案
使用$parents
数组,祖 parent 就是$parents[1]
。如果示例中的 grandParent
对象是最顶层的父对象,您也可以使用 $root
。
来自docs :
$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[2] is the view model from the great-grandparent context
… and so on.
$root
This is the main view model object in the root context, i.e., the topmost parent context. It’s usually the object that was passed to ko.applyBindings. It is equivalent to $parents[$parents.length - 1].
关于javascript - 在 knockout View 中访问 $parent 的 $parent - 嵌套上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17069381/