knockout:嵌套的dependentObservable - 不起作用

时间:2011-10-21 09:36:11

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

我是Knockout JS的新手。 我需要将嵌套数组绑定为folows

名称:下拉

电子邮件:所选用户的姓名

联系方式类型:从ContactInfo选择的联系方式类型下拉

联系人值:来自ContactInfo的实际值

我有姓名,电子邮件和联系人价值。我需要知道如何在下拉列表中选择联系方式类型值,同样需要绑定到联系人值。

我收到以下错误 错误:无法获取属性“ContactMethodType”的值:object为null或undefined

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>

1 个答案:

答案 0 :(得分:3)

您的问题在于您的第二个dependentObservable。默认情况下,dependentObservables在创建时首次进行评估。在您的情况下,selectedContactMethodType将获得selectedContactInfo的当前值null。这与undefined检查不符,然后尝试阅读导致错误的ContactMethodType null

因此,您需要更加小心地处理undefined与null的对比。

使用1.3 beta中的控制流绑定,这是您的示例,而不使用dependentObservables来防止null:http://jsfiddle.net/rniemeyer/9msqK/

相关问题