Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 406
Byron Sommardahl Avatar asked Dec 29 '11 00:12

Byron Sommardahl


2 Answers

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.

like image 143
Byron Sommardahl Avatar answered Sep 30 '22 01:09

Byron Sommardahl


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>
like image 36
John Papa Avatar answered Sep 30 '22 01:09

John Papa