Javascript 淘汰:嵌套的DependentToServable-不起作用
我对击倒JS还不熟悉。 我需要将嵌套数组绑定为follow 名称:下拉列表 电子邮件:所选用户名 联系方式类型:下拉列表,选择ContactInfo中的联系方式类型 联系人值:来自ContactInfo的实际值 我有名字,电子邮件和联系方式。我需要知道如何在下拉列表中选择contact method type值,并将其绑定到contact value 我得到以下错误 错误:无法获取属性“ContactMethodType”的值:对象为null或未定义Javascript 淘汰:嵌套的DependentToServable-不起作用,javascript,select,knockout.js,ko.observablearray,ko.dependentobservable,Javascript,Select,Knockout.js,Ko.observablearray,Ko.dependentobservable,我对击倒JS还不熟悉。 我需要将嵌套数组绑定为follow 名称:下拉列表 电子邮件:所选用户名 联系方式类型:下拉列表,选择ContactInfo中的联系方式类型 联系人值:来自ContactInfo的实际值 我有名字,电子邮件和联系方式。我需要知道如何在下拉列表中选择contact method type值,并将其绑定到contact value 我得到以下错误 错误:无法获取属性“ContactMethodType”的值:对象为null或未定义 function LifelineViewM
function LifelineViewModel() {
this.lifelines = ko.observableArray([{
Name: "",
Email: "",
ContactInfo:
{
ContactMethodType: "",
ContactValue: ""
}
}]);
this.selectedLifeline = ko.observable();
this.contactTypes = ko.observableArray([{Name: ''}]);
this.selectedContactInfo = ko.dependentObservable(function () {
if (this.selectedLifeline() === undefined) return null;
return this.selectedLifeline().ContactInfo;
}, this);
this.selectedContactMethodType = ko.dependentObservable(function () {
if (this.selectedContactInfo() === undefined) return null;
return this.selectedContactInfo().ContactMethodType;
}, this);
}
HTML代码
<select data-bind="options: lifelines, optionsText: 'Name', value: selectedLifeline"></select>
<p><span data-bind="text: selectedLifeline().Email"></span></p>
<p><span data-bind="text: selectedContactInfo().ContactMethodType + ' ' + selectedContactInfo().ContactValue"></p>
<select data-bind="options: contactTypes, optionsText: 'Name', value: selectedContactMethodType"></select>
您的问题在于您的第二个从属服务。默认情况下,DependentObservable在创建时第一次进行计算。在您的情况下,selectedContactMethodType
将从selectedContactInfo
获取当前值,该值将为null
。这与您的undefined
检查不匹配,然后尝试读取ContactMethodType
off的null
,这会导致错误
因此,在处理未定义与null时,您需要更加小心
使用中的控制流绑定,以下是不使用DependentToServable来防止null的示例:您的问题在于第二个DependentToServable。默认情况下,DependentObservable在创建时第一次进行计算。在您的情况下,
selectedContactMethodType
将从selectedContactInfo
获取当前值,该值将为null
。这与您的undefined
检查不匹配,然后尝试读取ContactMethodType
off的null
,这会导致错误
因此,在处理未定义与null时,您需要更加小心
使用中的控制流绑定,以下是您的示例,不使用DependentToServables来防止null: