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

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

问题描述

我有这样的结构:

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

...我需要能够 ko.applyBindings col1 col3 。现在,我正在做这样的事情来绑定到 col1

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

这可以很好地填充第一列。但我仍然缺乏第三栏。我希望能够做到这一点:

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

然后...

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

...因此它试图绑定到 .bindable的所有实例。有没有类似这样的淘汰赛,或者你有什么建议? 这是我找到的最佳解决方案:

 < div id ='col1'class ='bindable'> ...一些ko元素...< / div> 
< div id ='col2'>< / div>
< div id ='col3'class ='bindable'> ...一些更多的元素...< / 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天全站免登陆