knockout: nested dependenobservable -不起作用

knockout: nested dependentObservable - not functioning

本文关键字:不起作用 dependenobservable nested knockout      更新时间:2023-09-26

我是Knockout JS的新手。我需要像下面这样绑定嵌套数组

Name:下拉

Email:所选用户名

联系人方法类型:从ContactInfo中选择联系人方法类型下拉

接触值: ContactInfo中的实际值

我有名字,电子邮件和联系值工作。我需要知道如何在下拉菜单中选择接触方法类型值,同样需要绑定到接触值。

我得到以下错误错误:无法获取属性"ContactMethodType"的值:对象为空或未定义

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);

}

<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>

你的问题在于你的第二个dependenobservable。默认情况下,dependentObservables在创建时第一次被评估。在您的例子中,selectedContactMethodType将从selectedContactInfo获得电流值,即null。这将不匹配您的undefined检查,然后尝试从null中读取ContactMethodType,这会导致错误。

所以,你需要在如何处理undefined和null时更加小心。

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