我需要将两个 knockout View 模型绑定(bind)到一个 View 。我读过这样的示例和优惠
var viewModel1 = function(){
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.fullName = ko.computed(function(){
return self.firstName + " " + self.lastName;
});
};
var viewModel2 = function(){
var self = this;
self.premium = ko.observable();
};
ko.applyBindings(new viewModel1(), document.getElementById("container1"));
ko.applyBindings(new viewModel2(), document.getElementById("container2"));
但我的 View 模型位于单独的 js 文件中。如何将它们绑定(bind)到 View ?例如
<script>
$(function() {
window.viewModal1 = new CandidatesViewModal();
window.viewModal2 = new CandidatesViewModal();
});
ko.applyBindings(viewModal1 , $('#viewModal1 ').get(0));
ko.applyBindings(viewModal2 , $('#viewModal2 ').get(0));
</script>
但是这种方法行不通。感谢您的帮助。
最佳答案
您应该创建一个容器 View 模型,例如像这样:
var container = {
vm1: new viewModel1(),
vm2: new viewModel2()
}
ko.applyBindings(containerVm);
并相应地调整你的观点。
关于javascript - 将多个 knockout View 模型脚本绑定(bind)到一个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501892/