Knockout.js:页面或页面一部分上的多个ViewModel绑定 [英] Knockout.js: Multiple ViewModel bindings on a page or a part of a page

查看:155
本文介绍了Knockout.js:页面或页面一部分上的多个ViewModel绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以多次使用 Knockout.js ko.applyBindings()将不同的ViewModel绑定到页面的一部分.例如,假设我有这个:

I am wondering if it is possible to use Knockout.js's ko.applyBindings() multiple times to bind different ViewModels to one part of a page. For example, let's say I had this:

<div id="foo">...</div>
...
ko.applyBindings(new PageViewModel());
ko.applyBindings(new PartialViewModel(), $('#foo')[0]);

我现在将两个ViewModel绑定应用于<div id="foo>.这合法吗?

I am now applying two ViewModel bindings to <div id="foo>. Is this legal?

推荐答案

您不想在同一元素上多次调用ko.applyBindings.最好的情况是,元素将在更新时进行不必要的工作,更糟糕的是,您将为同一个元素触发多个事件处理程序.

You do not want to call ko.applyBindings multiple times on the same elements. Best case, the elements will be doing more work than necessary when updating, worse case you will have multiple event handlers firing for the same element.

这里有几种处理此类事件的选项:

There are several options for handling this type of thing that are detailed here: Example of knockoutjs pattern for multi-view applications

如果以后确实要在其上调用应用绑定的内容中间确实需要一个岛",则可以使用此处描述的技术:

If you really need an "island" in the middle of your content that you want to call apply bindings on later, then you can use the technique described here: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

这篇关于Knockout.js:页面或页面一部分上的多个ViewModel绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆