在KO组件的模板中访问$ root绑定上下文将返回页面的视图模型,而不是组件的视图模型。为什么这样,如何在不使用$ parent的情况下从嵌套绑定上下文中访问组件的视图模型?
以下示例代码段输出“test2”。
HTML:
<my-component></my-component>
JS:
ko.components.register("my-component", {
template: "<div data-bind='text: $root.test'></div>",
viewModel: function(params) { this.test = "test1" }
});
ko.applyBindings({ test: "test2" });
答案 0 :(得分:8)
目前您无法使用$ root绑定上下文作为组件上下文,但$ parent和$ parents []按预期工作,请参阅documentation。对于3.3版本中的页面,将有$ component绑定上下文与$ root相同,并且已经完成github。