我是 Knockout JS 的新手。 我需要如下绑定(bind)嵌套数组
名称:下拉列表
电子邮件:所选用户的姓名
联系方法类型:从 ContactInfo 中选择联系方法类型下拉列表
联系人值:来自 ContactInfo 的实际值
我已获取姓名、电子邮件和联系方式。我需要知道如何在下拉列表中选择联系方法类型值,并且同样需要绑定(bind)到联系值。
我收到以下错误 错误:无法获取属性“ContactMethodType”的值:对象为 null 或未定义
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>
最佳答案
您的问题在于您的第二个依赖Observable。默认情况下,dependentObservables 在创建时第一次被评估。在您的情况下,selectedContactMethodType
将从selectedContactInfo
获取当前值,该值将为null
。这与您的 undefined
检查不匹配,然后尝试从 null
读取 ContactMethodType
,这会导致错误。
因此,您需要更加小心地对待 undefined 与 null。
使用 1.3 beta 中的控制流绑定(bind),这是您的示例,没有使用 dependentObservables 来防止 null:http://jsfiddle.net/rniemeyer/9msqK/
关于javascript - knockout : nested dependentObservable - not functioning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7847543/