我有以下主视图模型
var masterVM = (function() {
this.PatientViewModel = ko.mapping.fromJS(new PatientViewModel());
this.MedicalBenefit = new MedicalBenefitViewModel(this.PatientViewModel);
})();
以及以下视图模型
var PatientViewModel = function() {
var self = this;
self.FirstName = ko.observable();
self.LastName = ko.observable();
self.NationalHealthFundId = ko.mapping.fromJS(null);
self.NationalHealthFundId.subscribe(function(newValue) {
alert("subscribe from patient");
});
};
var MedicalBenefitViewModel = function (patient) {
var self = this;
self.patient = patient;
};
和自定义绑定中的某个地方(绑定到患者):
...
var observable = valueAccessor();
ko.mapping.fromJS(patient, {}, observable);
...
患者是代表患者的简单普通json对象。
自定义绑定执行后,订阅(警报("从患者订阅");)停止工作,为什么?
答案 0 :(得分:1)
您已设置self.NationalHealthFundId = ko.mapping.fromJS(null);
。您只能订阅一个可观察者。例如,这有效:
var PatientViewModel = function() {
var self = this;
self.FirstName = ko.observable();
self.LastName = ko.observable();
self.NationalHealthFundId = ko.observable();
self.NationalHealthFundId.subscribe(function(newValue) {
alert("subscribe from patient");
});
};
var vm = new PatientViewModel()
ko.applyBindings(vm);
vm.NationalHealthFundId(1);
vm.NationalHealthFundId(2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
&#13;