0

我是Knockout JS的新手。 我需要綁定嵌套數組作爲folows淘汰賽:nested dependentObservable - 無法運作

名稱:降下來

電子郵件:選擇用戶名

聯繫方法類型:降下來,聯繫方式類型從的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> 

回答

3

你的問題在於你的第二個dependentObservab樂。默認情況下,dependentObservables在創建時第一次被評估。在你的情況下,selectedContactMethodType將從selectedContactInfo獲得當前值,這將是null。這與您的undefined檢查不符,然後嘗試從null中讀取ContactMethodType,這會導致錯誤。

因此,您需要在處理未定義與空值時更謹慎一點。

1.3 beta使用控制流綁定,這裏是不使用dependentObservables防止空你的樣品:http://jsfiddle.net/rniemeyer/9msqK/

+1

謝謝你RP尼邁耶。 KO 1.3讓我的工作更輕鬆。 KO ROCKS !!! –