KnockOutJS - Multiple ViewModels in a single View
Solution 1:
Knockout now supports multiple model binding. The ko.applyBindings()
method takes an optional parameter - the element and its descendants to which the binding will be activated.
For example:
ko.applyBindings(myViewModel, document.getElementById('someElementId'))
This restricts the activation to the element with ID someElementId
and its descendants.
See documentation for more details.
Solution 2:
If they all need to be on the same page, one easy way to do this is to have a master view model containing an array (or property list) of the other view models.
masterVM = {
vmA : new VmA(),
vmB : new VmB(),
vmC : new VmC(),
}
Then your masterVM
can have other properties if needed, for the page itself. Communication between the view models would not be difficult in this situation as you could relay through the masterVM
, or you could use the $parent
/ $root
in bindings, or some other custom options.