Knockout dependentObservable Firing Twice
-
14-11-2019 - |
문제
I'm using Castle Monorail & NVelocity View Engine. I have the following model:
var sampleModel ;
jQuery(function () {
var mappings = {
'DateSent': ko.utils.dateConversionFunc()
};
sampleModel = {
dto: ko.mapping.fromJS($dto, mappings),
ReasonOtherId: $reasonOtherId,
referralReasonOptions: $reasonOptions //$reasonOptions is a Json list
};
sampleModel.showOtherReason = ko.dependentObservable(function () {
alert(this.dto.referralReason());
return this.dto.referralReason() == this.ReasonOtherId;
}, sampleModel);
ko.applyBindings(sampleModel, jQuery('#referralContainer')[0]);
}
);
select data-bind="value : dto.referralReason, options: referralReasonOptions.Options, optionsText: 'DisplayName', optionsValue:'Id'">
If the dto.referralReason (or $dto) is empty , the sampleModel.showOtherReason will fires once and alert the Id. The strange thing is, if $dto is NOT empty, sampleModel.showOtherReason execute twice and two alert pop out, the first alert shows '1405', which is correct, but then it fires another alert which is "undefined". Does anyone know it is firing twice if there is any data? Thanks.
해결책
The value
binding when used with the options
binding tries to ensure that the value is a valid option.
In your case, it looks like 1405 is not a valid choice.
If you are using a version prior to 2.0, then your issue is likely that you need to swap the order of your value/options bindings. Prior to 2.0, options
needs to come first to build the options, then value
can set it to a valid option