Nesting multiple virtual machines with nested DIVs

I experience that the nested div does not bind to VM. Any ideas? I am trying to do the following and it breaks any ideas?

<div id="div1"> <div id="div2"> </div> </div> 

If I try, this works great:

 <div id="div1"> </div> <div id="div2"> </div> 

JavaScript:

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

Any ideas?

+4
source share
1 answer

When you bind div1 , it will bind everything that is in div2 . When you bind div2 , it will bind the elements again. This is not a good situation, as elements will have many event handlers associated with them. Otherwise, one of the applyBindings is most likely to be erroneous, because the elements do not expect to be bound to another view model.

This article describes how to protect an internal element from being bound by an external call: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

Another option is to use one view model, for example:

 var viewModel = { vm1: vm1, vm2: vm2 }; ko.applyBindings(viewModel); 

Then bind as:

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

All Articles