【问题标题】:knockout: nested dependentObservable - not functioning淘汰赛:嵌套的dependentObservable - 不起作用
【发布时间】:2011-10-21 22:22:52
【问题描述】:

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

名称:下拉

电子邮件:所选用户名

联系方法类型:从选择的 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);

}

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>

【问题讨论】:

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


    【解决方案1】:

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

    因此,在对待 undefined 与 null 的方式上,您需要更加小心。

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

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 2011-08-11
      • 2016-05-20
      • 2014-06-19
      相关资源
      最近更新 更多