Einarsson
Einarsson

Reputation: 522

Bind to property not yet initialized

I have a list and a details view at the same page. I use this to list contacts. When I click one contact in the list it sets a "selectedContact" property which my details view binds towards to display details about this chosen contact. However, before I have chosen a contact the binding crashes because the property isn't set yet. How can I achieve this?

JS general structure.

self.contacts = ko.observableArray();
self.selectedContact = ko.observable();

self.selectContact = function (contact) {
        self.selectedContact(contact);
        alert(self.selectContact.Name);
    }

HTML

<h3>
    <span data-bind="text: selectedContact.Name"></span>
</h3>
<div>
    <span data-bind="text: selectedContact.Number"></span>
</div>
<div>
    <span data-bind="text: selectedContact.Email"></span>
</div>

So simply. Loading this page crashes because selectedContact isn't set until I've clicked a contact in the list. Before then I don't really want it to display anything.

What is the simplest way? Thank you. :)

Upvotes: 1

Views: 158

Answers (1)

John Earles
John Earles

Reputation: 7194

Add a div outside, and structure it like this:

<div data-bind="with: selectedContact">
  <h3>
    <span data-bind="text: Name"></span>
  </h3>
  <div>
    <span data-bind="text: Number"></span>
  </div>
  <div>
    <span data-bind="text: Email"></span>
  </div>
</div>

The with binding will dynamically add or remove descendant elements depending on whether the associated value is null/undefined or not.

Upvotes: 2

Related Questions