【问题标题】:knockout: can't access parent scoped property from nested foreach淘汰赛:无法从嵌套的 foreach 访问父范围属性
【发布时间】:2016-03-30 11:09:42
【问题描述】:

我正在尝试从我的嵌套 foreach 中访问根级别属性。

<!-- ko foreach: { data: items, 'as': 'item' } -->
<tr data-bind="foreach: { data: $parent.columns, 'as': 'column' }" >
  <td>{{ item[column.key]  }}</td>
    <!-- ko if: $root.thing -->
    <td><button class="btn btn-default" >click me</button></td>
    <!-- /ko -->            
</tr>
<!-- /ko -->

thing 是一个普通对象,而不是可观察对象。 $root.thing 评估为假。我也试过$parent[1].thing。这给了我一个绑定错误Message: Cannot read property 'thing' of undefined,这很奇怪,因为我认为$root$parent[1] 在这种情况下是等价的。

编辑:此代码是组件的一部分。在视图中它看起来像这样:

<component data-bind="thing: {prop: 'foo'}, stuff: $data" />

在组件中,我们有:

return function(params) {
    this.thing = params.thing;
    this.items = params.stuff.items;
    this.columns = [{key: 'one'}, {key: 'two'}];
})

【问题讨论】:

  • 应该是$parents[1],相当于root。尽管这可能无法解决您的问题,因为 $parents[1].thing 仍然是错误的。显示更多代码(但不是全部),如您的视图模型会有所帮助。
  • 实际上,$parents[1].thing 有效,但我仍然想知道为什么 $root 无效。是因为它是一个组件吗?
  • 哦,我明白了,这是来自组件,好吧$root 将不起作用,因为它会查看您的视图模型的根变量。
  • 是的,我可以从淘汰赛 3.3 开始使用 $component。
  • 是的,如果您在特定组件模板的上下文中,$component 是 $root 等价物。但我想评论你的回答,$root 在组件上工作,它不会查看组件的基本变量,而是查看视图模型中的成员变量,即你在 applyBindings 中传递的模型.

标签: javascript knockout.js


【解决方案1】:

$root 引用视图模型,而不是组件,使用$parents[]。从淘汰赛 3.3 开始,您还可以使用$component

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2014-12-11
    • 1970-01-01
    • 2011-08-11
    • 2013-03-27
    • 2013-04-20
    • 2013-05-15
    • 1970-01-01
    相关资源
    最近更新 更多