KnockOutJS – Multiple ViewModels in a single View

data-bindingknockout-mapping-pluginknockout.jsmvvm

I'm thinking that my application is getting quite large now, too large to handle each View with a single ViewModel.

So I'm wondering how difficult it would be to create multiple ViewModels and load them all into a single View. With a note that I also need to be able to pass X ViewModel data into Y ViewModel data so the individual ViewModels need to be able to communicate with each other or at least be aware of each other.

For instance I have a <select> drop down, that select drop down has a selected state which allows me to pass the ID of the selected item in the <select> to another Ajax call in a separate ViewModel….

Any points on dealing with numerous ViewModels in a single View appreciated 🙂

Best Answer

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.

Related Topic