Sandeep G B
Sandeep G B

Reputation: 4015

knockout: nested dependentObservable - not functioning

I am new to Knockout JS. I need to bind nested arrays as folows

Name: Drop down

Email: Selected user's name

Contact Method Type: Drop down with Contact Method type from ContactInfo selected

Contact Value: Actual value from ContactInfo

I have got Name, email and contact value working. I need to know how to have contact method type value being selected in the drop down and the same need to be bound to contact value.

I get following error Error: Unable to get value of the property 'ContactMethodType': object is null or 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 code

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

Upvotes: 0

Views: 1110

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

Your issue lies in your second dependentObservable. By default, dependentObservables are evaluated for the first time when they are created. In your case, selectedContactMethodType will get the current value from selectedContactInfo which will be null. This will not match your undefined check and then try to read ContactMethodType off of null which causes the error.

So, you would need to be a bit more careful in how you treat undefined vs. null.

Using the control-flow bindings in 1.3 beta, here is your sample without using dependentObservables to protect against null: http://jsfiddle.net/rniemeyer/9msqK/

Upvotes: 3

Related Questions