Farhad-Taran
Farhad-Taran

Reputation: 6540

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

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

Upvotes: 4

Views: 2646

Answers (3)

FIRAT OLTULU
FIRAT OLTULU

Reputation: 1

You can use

ko.applyBindings(viewModel, element) 

OR

"With" binding

Upvotes: 0

rxjmx
rxjmx

Reputation: 2181

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

Upvotes: 9

dfperry
dfperry

Reputation: 2258

Check out the reference docs: http://knockoutjs.com/documentation/observables.html

the ko.applyBindings function takes two params, the first is the viewmodel, the second (optional) is the dom element to which it should be applied. You can apply multiple viewmodels to each container element on your page.

ko.applyBindings(viewmodel1, $("#container1")[0]);
ko.applyBindings(viewmodel2, $("#container2")[0]);
ko.applyBindings(viewmodel3, $("#container3")[0]);

Upvotes: 2

Related Questions