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

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

问题描述

我想知道是否可以多次使用 Knockout.jsko.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.

这里详细介绍了处理此类事情的几种选择:多视图应用的knockoutjs模式示例

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

如果你真的需要在你的内容中间有一个岛",你想稍后调用应用绑定,那么你可以使用这里描述的技术:http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

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天全站免登陆