敲除 JS foreach $root undefined

Knockout JS foreach $root undefined

我正在尝试在 Knockout JS 中创建一个广播组,这是模板代码

<p>Selected Plan <div data-bind="text: selectedPlan"></div></p>
<div data-bind="foreach: plans">
    <label>
        <input type="radio" name="plan" data-bind="attr: {value: id}, checked: $root.selectedPlan"/>
        <span data-bind="html: title"></span>
        <div data-bind="text: desc"></div>
    </label>
</div>

在组件selectePlanplans注册如下

this.plans = ko.observableArray([/* array of plans */]);
this.selectedPlan = ko.observable('xxxxx');

我已验证 xxxxxthis.plans 中的有效条目。尽管如此,控制台中还是出现了错误

knockout.js:3391 Uncaught TypeError: Unable to process binding "foreach: function(){return plans }" Message: Unable to process binding "checked: function(){return $root.selectedPlan }" Message: Cannot read property 'selectedPlan' of undefined

由于某种原因,$root 关键字似乎是 undefined...

编辑: 计划结构

[{
 id: 'xxxxx',
 desc: 'This is a great plan',
 title: '<strong>Save with great plan</strong>',
},
...
]

看看这个例子:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<p>Selected Plan
  <b><span data-bind="text: selectedPlan"></span></b>
</p>
<div data-bind="foreach: plans">
  <label>
    <input type="radio" name="plan" data-bind="value: title, checked: $parent.selectedPlan"/>
    <span data-bind="html: title"></span>
    <span data-bind="text: desc"></span>
  </label>
</div>

<script type="text/javascript">
  var viewModel = {
    plans: ko.observableArray([
      {id: 1, desc: 'Red Foo', title: 'Foo'}, 
      {id: 2, desc: 'Blue Bas', title: 'Bas'}
    ]),
    selectedPlan: ko.observable()
  };
  ko.applyBindings(viewModel);
</script>

我做了一些改动:

  1. 没有使用 attr 绑定,而是直接使用 valuechecked
  2. 我使用 $parent 达到顶层,但 $root 也能正常工作
  3. 我稍微更改了 html 使其在一行等

我知道这已经得到解答,但我认为您仍然想知道为什么 $root 未定义(我会)。我可以看到您到处都在谈论 'component'。可能就像您只是试图获取组件的根一样简单,因此 $component?

来自淘汰赛现场:

$component

If you’re within the context of a particular component template, then $component refers to the viewmodel for that component. It’s the component-specific equivalent to $root. In the case of nested components, $component refers to the viewmodel for the closest component.

This is useful, for example, if a component’s template includes one or more foreach blocks in which you wish to refer to some property or function on the component viewmodel rather than on the current data item.

请查看 Knockout Binding Context 页面了解更多信息。