您正在绑定到两个独立视图模型实例
ko.applyBindings(new viewModel1(), document.getElementById("firstViewModel"));
ko.applyBindings(new viewModel2(), document.getElementById("secondViewModel"));
所以你的viewModel1 和viewModel2 之间没有联系,当你写在你的viewModel1 时:
var vm2Object = new viewModel2();
那么您正在创建一个全新的viewModel2 实例,它与applyBindings 中使用的实例无关。
要解决此问题,您需要在视图模型之间建立连接,就像这样(还有多种其他方法可以做到,例如使用容器视图模型、将视图模型相互嵌套等):
var viewModel1 = function(vm2){
var self = this;
var vm2Object = vm2; //use vm from parameter
//...
}
当调用applyBindings:
var vm2 = new viewModel2();
ko.applyBindings(new viewModel1(vm2), document.getElementById("firstViewModel"));
ko.applyBindings(vm2, document.getElementById("secondViewModel"));
演示JSFiddle.