javascript - knockout : nested dependentObservable - not functioning

标签 javascript select knockout.js ko.observablearray ko.dependentobservable

我是 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/

相关文章:

php - 根据之前的选择以及数据库中的值创建多个选择

python - 在 python3 中比较字符串和解码后的 unicode

javascript - Knockout.js,依赖于 Observable 的条件 Observable?

javascript - 为什么我不能在 html dom 上使用 javascript 将宽度和高度添加到我的 div

javascript - 在javascript中刷新页面时阻止变量的更改值

javascript - Openlayers 绘图的某些部分是不可见的

Mysql:使用选择和局部变量更新

html - knockout.js 数据绑定(bind)不能同时具有模板和值

javascript - knockout 映射——将多个数据源整合到一个 View 模型中

javascript不会从数组生成