我知道如何绑定到属性,但我如何绑定到属性,如: Parent.Child
在Knockout JS.com上使用hello world示例: 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"));
我想创建一个与childProperty的绑定。
我创建了jsfiddle here
由于
答案 0 :(得分:28)
非常接近!
你想要
<span data-bind="text: parentProperty().childProperty"> </span>
您的更新小提琴http://jsfiddle.net/szk2e/2/
答案 1 :(得分:17)
在这里添加答案,因为这最适合我的特定情况......
有一种情况,蒂姆的答案不会奏效。这是父属性可以是undefined
的时候。
例如,如果您正在使用 itemsSource 和 selectedItem 的常见模式(用户从列表中选择单个项目) selectedItem 在首次评估时未定义,并且每当用户撤消其选择时。使用绑定text:selectedItem().SomeProperty
将&#34;打破&#34;淘汰赛,防止评估绑定。请注意,尝试使用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 binding将动态添加或删除后代元素,具体取决于相关值是否为null / undefined
如果您还需要隐藏容器,具体取决于属性是否未定义,那么您应该使用<!-- ko -->
虚拟元素来包围容器。 More information can be found here.