我正在嘗試解決如何將多個模型從主模型綁定到HTML標記的不同部分。 HTML部分是: -在KnockoutJs中綁定多個視圖模型
<ul data-bind="foreach: { data: members}">
<li>
<span data-bind="text: MemberId"></span>
<span data-bind="text: Name"></span>
<span data-bind="text: SwagCompany"></span>
<span data-bind="text: SwagThing"></span>
</li>
</ul>
<span data-bind="text: winner.Name"></span>
但無法工作,如何綁定winner.Name
,我的模型是這樣的: -
var masterViewModel = {
vmA : { ...},
vmB : { ... }
}
ko.applyBindings({
winner: ko.observable(masterViewModel.vmB),
members: ko.observableArray(mappedData),
...
}
顯然我誤解如何正確applyBindings。我有以下的代碼作爲plunker呈現出什麼,我試圖做一個例子: -
<script>
$(function() {
var masterViewModel = {
vmA: function memberViewModel(data) {
this.Id = data.MemberId;
this.MemberId = ko.observable(data.MemberId);
this.Name = ko.observable(data.Name);
this.SwagCompany = ko.observable("");
this.SwagThing = ko.observable("");
this.Photo = ko.observable(data.Photo);
},
vmB: {
Name: "Initial winner..."
}
};
$.getJSON("/home/memberlist")
.then(function (rawData) {
return ko.utils.arrayMap(rawData, function (instanceData) {
return new masterViewModel.vmA(instanceData);
});
})
.done(function (mappedData) {
doit(mappedData);
});
function doit(mappedData) {
ko.applyBindings({
winner: ko.observable(masterViewModel.vmB),
members: ko.observableArray(mappedData),
getNextWinner: function() {
var members = this.members();
var winner = this.winner();
//console.log(ddd.Name());
$.getJSON("/home/nextwinner")
.then(function (rawData) {
var nextWinner = ko.utils.arrayFirst(members, function (member) {
return member.Id === rawData.Winner.MemberId;
});
nextWinner.SwagThing(rawData.WonSwag.Thing);
nextWinner.SwagCompany(rawData.WonSwag.Company);
winner.Name(rawData.Winner.Name);
});
}
});
}
});
</script>
我同意@ xdumaine的回答。如果您正確應用MVVM模式,則只需創建並綁定視圖模型一次。與其試圖通過重新綁定到新視圖模型實例來更改頁面內容,您應該能夠簡單地修改加載頁面時綁定的視圖模型實例。 –