最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can I applyBindings to more than one DOM element using Knockout? - Stack Overflow

programmeradmin4浏览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?

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?

Share Improve this question edited Dec 29, 2011 at 6:14 Charles 51.4k13 gold badges106 silver badges144 bronze badges asked Dec 29, 2011 at 0:09 Byron SommardahlByron Sommardahl 13k17 gold badges80 silver badges132 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

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.

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>
发布评论

评论列表(0)

  1. 暂无评论