aanmelden
home web developer multiple vms with knockout

Multiple VMs with knockout

Laatst gewijzigd: vrijdag 5 april 2013 om 10:55

This morning I have been playing with knockoutjs. It is great! After finishing the first tutorial, I was wondering if it would be possible to use multiple view models. The answer is yes. It is possible to bind part of the view to a specific model. You can do this by specifying an element to which to apply the binding. See the documentation for more details. In my case, I used the following bindings:

ko.applyBindings(new AppViewModel()); ko.applyBindings(new MyViewModel(), document.getElementById('mine'));

After I added this, the first model behaved as before, but a script error occurred, saying the elements that I added could not be bound. The solution was simple, although it took me some time. What the documentation does not mention (because it goes without saying) is that you must register each model to a specific view:

ko.applyBindings(new AppViewModel(), document.getElementById('default')); ko.applyBindings(new MyViewModel(), document.getElementById('mine'));

After I did this, everything worked fine.