Nesting multiple VMs with nested DIVs

2019-02-13 21:04发布

问题:

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:

ko.applyBindings(vm1, document.getElementById('div1'));
ko.applyBindings(vm2, document.getElementById('div2'));

Any ideas?

回答1:

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);

Then, bind like:

<div id="div1" data-bind="with: vm1">
   <div id="div2" data-bind="with: $root.vm2">

   </div>
</div>


标签: knockout.js