18

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

4

2 回答 2

28

So so very close!

You want

<span data-bind="text: parentProperty().childProperty"> </span>

Your updated fiddle http://jsfiddle.net/szk2e/2/

于 2012-04-10T15:20:59.517 回答
18

在此处添加答案,因为这最适合我的特定情况...

有一种情况是蒂姆的回答不起作用。这时候父属性就可以了undefined

例如,如果您使用itemsSourceselectedItem的通用模式(用户从列表中选择单个项目),则selectedItem将在第一次评估时未定义,并且无论何时用户撤消他们的选择。使用绑定text:selectedItem().SomeProperty将“打破”淘汰赛,防止绑定被评估。visible请注意,尝试使用绑定(例如, )将其短路是text:selectedItem().SomeProperty, visible:selectedItem行不通的。

在这种情况下,您必须使用绑定with绑定上下文切换到属性的值。所以,使用OP的例子......

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

请注意,此绑定的行为是(来自文档)

with 绑定将根据关联值是否为空/未定义来动态添加或删除后代元素

如果你还需要根据属性是否未定义来隐藏容器,那么你应该使用<!-- ko -->虚拟元素来包围容器。 更多信息可以在这里找到。

于 2014-09-01T20:02:25.347 回答