为什么在 table 行中使用数据绑定 ='if' 时会出现 Knockout js 的 ReferenceError

Why do I get a ReferenceError for Knockout js when using a data-bind ='if' in a table row

我有点困惑。当我尝试在 td 标记中调用 "if:(showActiveOnly)" 时,我得到 "ReferenceError: showActiveOnly is not defined",但我立即在它下面放置了一个 p 标记作为测试并将其数据绑定设置为 "text:showActiveOnly",并且这是阅读发现。我错过了什么?

var viewmodel = {
            userList:UserListViewModel(users),
            showActiveOnly : ko.observable(true)
        }
        ko.applyBindings(viewmodel);

<div>
    <div>
        <input type="checkbox" data-bind="checked: showActiveOnly" /><p data-bind="text:$data.showActiveOnly"></p>

        <table >
            <thead>
                <tr data-bind="click: sortTable">
                    <th>
                        User Name
                    </th>
                </tr>
            </thead>
            <tbody data-bind="foreach: currentPage ">
                <tr data-bind="if:(showActiveOnly)">
                    <p data-bind="text:showActiveOnly"></p>
                    <td data-bind="text: Username" style="width: 10%;"></td>
                </tr>
            </tbody>
        </table>

错误:未捕获的错误:无法解析绑定。 消息:ReferenceError:未定义 showActiveOnly; 绑定值:if(showActiveOnly)

稍微更改了答案。我认为问题在这里 scope/context。但也有我认为您可能希望通过此 table 实现的建议。这里演示了使用 virtual element 而不是 tr 元素而不是 tbody 上的 foreach。

我认为你想要的例子。也就是说,如果每个 currentPage 都有一个 showActiveOnly 可观察对象。如果 showActiveOnly 不存在于每个 currentPage 上,您可以使用 $parent、$parents[index] 或 $root 来获取该可观察对象的正确范围。如此处所述 https://knockoutjs.com/documentation/binding-context.html

<tbody>
    <tr data-bind="foreach: currentPage ">
        <!-- ko if: showActiveOnly -->
        <p data-bind="text:showActiveOnly"></p>
        <td data-bind="text: Username" style="width: 10%;"></td>
        <!-- /ko -->
    </tr>
</tbody>

试试这个:

 <tbody data-bind="foreach: currentPage ">
                <tr data-bind="if: $parent.showActiveOnly">
                    <p data-bind="text:showActiveOnly"></p>
                    <td data-bind="text: Username" style="width: 10%;"></td>
                </tr>
            </tbody>

因为您使用的是 foreach,所以您正在更改所包含绑定的上下文。 这就是您必须使用 $parent 或 $root 的原因。在 knockoutJS 站点搜索 knockout 数据上下文信息,它包含所有细节!