I know how to bind to a property, but how do i bind to a property like:
Parent.Child
Using the hello world example on Knockout JS.com:
Html:
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
<h2>ChildProperty: <span data-bind="text: parentProperty.childProperty"> </span>!</h2>
Javascript:
var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.parentProperty = ko.observable(
{
childProperty: "I am a child Property"
});
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));
I would like to create a binding to the childProperty.
I created a jsfiddle here
Thanks
So so very close!
You want
<span data-bind="text: parentProperty().childProperty"> </span>
Your updated fiddle http://jsfiddle.net/szk2e/2/
Adding an answer here as this is the best fit to my particular situation...
There is a situation where Tim's answer won't work. This is when the parent property can be undefined
.
For example, if you're using the common pattern of itemsSource and selectedItem (where the user selects a single item from a list) selectedItem will be undefined on first evaluation, and whenever the user has undone their selection. Using the binding text:selectedItem().SomeProperty
will "break" knockout, preventing bindings from being evaluated. Note, trying to short circuit this using the visible
binding (e.g., text:selectedItem().SomeProperty, visible:selectedItem
) will NOT work.
In this case, you have to use the with
binding to switch the binding context to the value of the property. So, using OP's example...
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
<h2 data-bind="with:parentProperty">ChildProperty:
<span data-bind="text: childProperty"></span>!
</h2>
Note that the behavior for this binding is (from the docs)
The with binding will dynamically add or remove descendant elements depending on whether the associated value is null/undefined or not
If you also need to hide the container depending on whether the property is undefined or not, then you should use the <!-- ko -->
virtual element to surround the container. More information can be found here.