Multiple ViewModels — one for page, one for div

356 views
Skip to first unread message

Adam

unread,
Sep 14, 2011, 10:33:06 AM9/14/11
to KnockoutJS
I'm trying to bind one viewModel to my entire page, and another one
just for a small little div somewhere inside of my page. I tried
this:

ko.applyBindings(viewModel);
ko.applyBindings(pagerViewModel, $("#pager").get(0));

But that caused problems, since #pager didn't like having the wrong
ViewModel applied to it, even for just a moment. I worked around this
simply by specifying each section that my main ViewModel needed, but I
was wondering if there was a better way

ko.applyBindings(viewModel, $("#contentParent").get(0));
ko.applyBindings(viewModel, $("#topSearchDiv").get(0));
ko.applyBindings(viewModel, $("#treeWrapper").get(0));
ko.applyBindings(pagerViewModel, $("#pager").get(0));

Mark Hahn

unread,
Sep 14, 2011, 4:20:32 PM9/14/11
to knock...@googlegroups.com
I use a method that works well for me. I combine multiple viewmodels
into one big viewmodel like this ...

viewmodel = {
vm1: {
... viewmodel 1 stuff ...
},
vm2: {
... viewmodel 2 stuff ...
}

I set each small viewmodel separately with ko.mappings. And then I
bind the entire big viewmodel once to the page. The data-bind
attributes look like ...

data-bind="text: vm1.name()"
data-bind="text: vm2.partnum()"

This way I can put any viewmodel binding anywhere on the page all at
once. Works great. This works better than namespaces and it solves
your problem.

Adam

unread,
Sep 14, 2011, 4:27:01 PM9/14/11
to KnockoutJS
That looks great. Thanks.
Reply all
Reply to author
Forward
0 new messages