Can I applyBindings to more than one DOM element using Knockout?

痞子三分冷 提交于 2020-01-21 03:04:07

问题


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?


回答1:


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.




回答2:


Looking at this from another angle, you only have 1 view model. So why not wrap the entire set of div's (col1, col2, etc) with a div and bind your viewmodel to it?

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


来源:https://stackoverflow.com/questions/8662743/can-i-applybindings-to-more-than-one-dom-element-using-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!