简体   繁体   English

淘汰赛:如何将多个局部视图模型应用于同一元素

[英]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. 我从这个问题和答案中了解到,我可以使用KnockoutJS将2个不同的视图模型绑定到2个不同的元素。

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? 但是,有没有办法将2个局部视图模型绑定到同一元素?

// 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? 或者,KnockoutJS是否可以将部分视图模型组合到单个视图模型中?

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. 先前的Stackoverflow答案似乎说“没办法”,但是我在问是否有新添加的淘汰赛选项,或者有人对我的困境有很好的解决方法。

// 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). 我问是因为2个局部视图模型是由单独的进程创建的(在Visual Studio中,有2个不同的t4脚本分别创建2个局部视图)。

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). 如果没有简单的解决方法,我可以将2个t4脚本重构为一个脚本,但这需要适度的重新布线(如果可能的话,我宁愿避免这样做)。

Any other alternatives? 还有其他选择吗?

You could create a single view model and use data-binding with to change context. 您可以创建一个单一的视图模型,并使用数据绑定来更改上下文。

Edit: jsFiddle 编辑: 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM