I have following master viewmodel
var masterVM = (function() {
this.PatientViewModel = ko.mapping.fromJS(new PatientViewModel());
this.MedicalBenefit = new MedicalBenefitViewModel(this.PatientViewModel);
})();
and following view models
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;
};
and somewhere in custom binding (bind to patient):
...
var observable = valueAccessor();
ko.mapping.fromJS(patient, {}, observable);
...
where patient is simple plain json object representing patient.
After custom binding execution, the subscription ( alert("subscribe from patient"); ) stops working, why ?
You have set self.NationalHealthFundId = ko.mapping.fromJS(null);
. You can only subscribe to an observable. For example, this works:
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>