首页 > 解决方案 > Knockout components and other viewModels coexistence

问题描述

I've learnt that after registering a knockout component, one should call ko.applyBindings() without argument. However, when defining another viewModel without components, let's call it vm, one should call ko.applyBindings(new vm()). Now when I try to use both in parallel, I get an error

You cannot apply bindings multiple times to the same element.

See also this fiddle

What can I do to make this work?

标签: javascriptmvvmknockout.js

解决方案


我找到了答案。问题是你不能在applyBindings没有第二个参数(也就是绑定范围的 HTML 元素)的情况下调用两次。对于我的组件,我很乐意提供第二个参数,即组件本身,但这在文档中不存在,您所能找到的只是applyBindings()没有任何参数。所以,通过反复试验,我发现

ko.applyBindings(null, document.getElementById('id'))

作为组件 HTML 元素的idid,有效。


推荐阅读