我可以使用 Knockout 将绑定应用到多个 DOM 元素吗? [英] Can I applyBindings to more than one DOM element using Knockout?

查看:18
本文介绍了我可以使用 Knockout 将绑定应用到多个 DOM 元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的结构:

... 一些 ko 元素 ... </div><div id='col2'></div><div id='col3'>...更多的 ko 元素 ... </div>

...而且我需要能够将 ko.applyBindings 应用到 col1col3.现在,我正在做这样的事情来绑定到 col1:

ko.applyBindings(myViewModel, document.getElementById("col1"));

可以很好地填充第一列.但我仍然缺少第三列.我很想能够做到这一点:

... 一些 ko 元素 ... </div><div id='col2'></div><div id='col3' class='bindable'>...更多的 ko 元素 ... </div>

然后……

ko.applyBindings(myViewModel, $(".bindable"));

... 以便它尝试绑定到 .bindable 的所有实例.淘汰赛有没有这样的事情,或者你有什么建议?

解决方案

这是我找到的最佳解决方案:

... 一些 ko 元素 ... </div><div id='col2'></div><div id='col3' class='bindable'>...更多的 ko 元素 ... </div>

然后是绑定的脚本...

$(".bindable").each(function(){ko.applyBindings(myViewModel, this[0]);}

这对我有用,而且很干净.

I've got a structure like this:

<div id='col1'> ... some ko elements ... </div>
<div id='col2'></div>
<div id='col3'> ... some more ko elements ... </div>

... and I need to be able to ko.applyBindings to col1 and col3. Right now, I'm doing something like this to bind to col1:

ko.applyBindings(myViewModel, document.getElementById("col1"));

That works fine to populate the first column. But I still lack the third column. I'd love to be able to do this:

<div id='col1' class='bindable'> ... some ko elements ... </div>
<div id='col2'></div>
<div id='col3' class='bindable'> ... some more ko elements ... </div>

And then...

ko.applyBindings(myViewModel, $(".bindable"));

... so that it attempts to bind to all instances of .bindable. Is there anything like this in knockout, or do you have any suggestions?

解决方案

Here's the best solution I've found:

<div id='col1' class='bindable'> ... some ko elements ... </div>
<div id='col2'></div>
<div id='col3' class='bindable'> ... some more ko elements ... </div>

And then the script that binds...

$(".bindable").each(function(){
    ko.applyBindings(myViewModel, this[0]);
}

This works for me and it's nice and clean.

这篇关于我可以使用 Knockout 将绑定应用到多个 DOM 元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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