【发布时间】: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 中传递的模型.