javascript - 在 knockout View 中访问 $parent 的 $parent - 嵌套上下文

标签 javascript knockout.js

为简洁起见进行了更新

如何在嵌套的 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/

相关文章:

javascript - 使用 knockout.js 时应该如何定义方法?

javascript - 如何使用 knockout 可观察变量删除 html 内部的 Html 元素

javascript - 如果时间已过,则从选择框中删除代表时间的项目

javascript - 根据div高度排列控件

javascript - XMLHttpRequest onload 属性?

knockout.js - 阵列的 knockout 阵列

javascript - 可空对象属性上的 Knockout js 绑定(bind)

javascript - 事件菜单选项卡

Javascript 和 jQuery 都停止删除 for 循环中的选项

javascript - 如何连接文本绑定(bind)中使用的可观察值的值?