敲除视图模型映射停止订阅触发

Knockout viewmodel mapping stops subscription firing

我有以下主视图模型

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);

...

其中 patient 是代表患者的简单 json 对象。

执行自定义绑定后,订阅( alert("subscribe from patient"); )停止工作,为什么?

您已设置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>