Nesting multiple VMs with nested DIVs

后端 未结 1 426
醉梦人生
醉梦人生 2021-01-05 21:32

I am experiencing that the nested div wont bind with the VM. Any ideas?I am trying the following and it breaks any ideas?

相关标签:
1条回答
  • 2021-01-05 21:48

    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>
    
    0 讨论(0)
提交回复
热议问题