使用嵌套的DIV嵌套多个VM [英] Nesting multiple VMs with nested DIVs
问题描述
我遇到了嵌套的div无法与VM绑定的问题.有什么想法吗?我正在尝试以下方法,但会破坏任何想法吗?
I am experiencing that the nested div wont bind with the VM. Any ideas?I am trying the following and it breaks any ideas?
<div id="div1">
<div id="div2">
</div>
</div>
如果我尝试这样做,效果很好:
If I try this is works fine:
<div id="div1">
</div>
<div id="div2">
</div>
JavaScript:
Javascript:
ko.applyBindings(vm1, document.getElementById('div1'));
ko.applyBindings(vm2, document.getElementById('div2'));
有什么想法吗?
推荐答案
绑定div1
时,它将绑定包括div2
中所有内容的所有内容.绑定div2
时,它将再次绑定元素.这不是一个好情况,因为元素将具有多个附加的事件处理程序.否则,由于元素不希望绑定到其他视图模型,因此applyBindings之一可能会出错.
When you bind div1
it will bind everything including what is in div2
. When you bind div2
it will bind the elements again. This is not a good situation, as elements will have multiple event handlers attached to them. Otherwise, one of the applyBindings will likely error out as the elements are not expecting to bind against a different view model.
The article here lays out a way to protect the inner element from being bound by the outer call: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html
另一种选择是使用单个视图模型,例如:
The other option is to use a single view model like:
var viewModel = {
vm1: vm1,
vm2: vm2
};
ko.applyBindings(viewModel);
然后,像这样绑定:
<div id="div1" data-bind="with: vm1">
<div id="div2" data-bind="with: $root.vm2">
</div>
</div>
这篇关于使用嵌套的DIV嵌套多个VM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!