Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js: Multiple ViewModel bindings on a page or a part of a page

Tags:

I am wondering if it is possible to use Knockout.js's ko.applyBindings() multiple times to bind different ViewModels to one part of a page. For example, let's say I had this:

<div id="foo">...</div> ... ko.applyBindings(new PageViewModel()); ko.applyBindings(new PartialViewModel(), $('#foo')[0]); 

I am now applying two ViewModel bindings to <div id="foo>. Is this legal?

like image 994
ecbrodie Avatar asked Dec 26 '12 20:12

ecbrodie


1 Answers

You do not want to call ko.applyBindings multiple times on the same elements. Best case, the elements will be doing more work than necessary when updating, worse case you will have multiple event handlers firing for the same element.

There are several options for handling this type of thing that are detailed here: Example of knockoutjs pattern for multi-view applications

If you really need an "island" in the middle of your content that you want to call apply bindings on later, then you can use the technique described here: http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html

like image 179
RP Niemeyer Avatar answered Sep 26 '22 23:09

RP Niemeyer