使用嵌套的 DIV 嵌套多个 VM [英] Nesting multiple VMs with nested DIVs

查看:19
本文介绍了使用嵌套的 DIV 嵌套多个 VM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到嵌套 div 无法与 VM 绑定的情况.有什么想法吗?我正在尝试以下方法,但它打破了任何想法?

<div id="div2">

如果我尝试这很好用:

<div id="div2">

Javascript:

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

有什么想法吗?

解决方案

当您绑定 div1 时,它将绑定所有内容,包括 div2 中的内容.当您绑定 div2 时,它将再次绑定元素.这不是一个好情况,因为元素将有多个事件处理程序附加到它们.否则,applyBindings 之一可能会出错,因为元素不希望绑定到不同的视图模型.

这里的文章列出了一种保护内部元素不受外部调用绑定的方法:http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

另一种选择是使用单个视图模型,例如:

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

然后,像这样绑定:

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

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?

解决方案

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>

这篇关于使用嵌套的 DIV 嵌套多个 VM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆