Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to bind several view models in a single page using knockout?

Tags:

knockout.js

I want to set my page up as a single page app using knockout, I have split it up as shown in the following picture but have no idea as to how to bind several viewModels into the same html page. enter image description here

like image 379
Farhad-Taran Avatar asked Dec 20 '22 05:12

Farhad-Taran


1 Answers

You can use ko.applyBindings(viewModel, element) to apply bindings to different elements, using different ViewModels like this: You cannot bind more than one viewModel to the same element or knockout will throw an error.

// Element
var element = document.getElementById('myElement');
ko.applyBindings(new MyViewModel(), element);

// Element 1
var element1 = document.getElementById('myElement1');
ko.applyBindings(new MyViewModel1(), element1);

You can read more about this here:

http://knockoutjs.com/documentation/observables.html

like image 98
rjmacarthy Avatar answered May 23 '23 03:05

rjmacarthy