JustAsking
JustAsking

Reputation: 149

Knockout: How to apply multiple partial view models to the same element

I understand from this question & answer that I can use KnockoutJS to bind 2 different view models to 2 different elements.

var viewModel1={...}
var viewModel2={...}

<div id="one"></div>
<div id="two"></div>

ko.applyBindings(viewModel1, document.getElementById('one'));
ko.applyBindings(viewModel2, document.getElementById('two'));

But, is there a way to bind 2 partial view models to the same element?

// This did not work for me

<div id='container'>
    <span data-bind='text: firstname' />
    <span data-bind='text: lastname' />   
</div>

var partialVM1={
    firstname:'John',
}
var partialVM2={
    lastname:'Adams',
}

var container=document.getElementById('container');
ko.applyBindings(partialVM1,container);
ko.applyBindings(partialVM2,container);

Or alternatively, does KnockoutJS have a way of combining partial viewmodels into a single view model?

Prior Stackoverflow answers appear to say "no way", but I'm asking if there are there newly added Knockout options or if someone has a nice workaround for my dilemma.

// Pseudo-code:
var combinedVM = ko.combine(partialVM1,partialVM2);
ko.applyBindings(combinedVM,container);

I ask because the 2 partial view models are being created by separate processes (In Visual Studio, there are 2 different t4 scripts that create the 2 partial views separately).

If there is no easy workaround, I could refactor the 2 t4 scripts into a single script, but that would require a modest bit of rewiring (I'd rather avoid it, if possible).

Any other alternatives?

Upvotes: 0

Views: 714

Answers (1)

Eric Kelly
Eric Kelly

Reputation: 452

You could create a single view model and use data-binding with to change context.

Edit: jsFiddle

Example:

<div id='container'>
    <div id='context1' data-bind='with: partial1'>
    <span  data-bind='text: firstname' />
    </div>
    <div id='context2' data-bind='with: partial2'>
    <span data-bind='text: lastname' />   
    </div>
</div>


var partialVM1={
    firstname:'John',
}
var partialVM2={
    lastname:'Adams',
}

var combined = (function () {
            function combinedVM() {
                this.partial1 = ko.observable(partialVM1);
                this.partial2 = ko.observable(partialVM2);
            }
            return combinedVM;
        })();


var container=document.getElementById('container');
ko.applyBindings(combined,container);

Upvotes: 1

Related Questions