And*_*dre 18 javascript knockout.js
我知道如何绑定到属性,但我如何绑定到像以下属性: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>
Run Code Online (Sandbox Code Playgroud)
使用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"));
Run Code Online (Sandbox Code Playgroud)
我想创建一个绑定到childProperty.
谢谢
Tim*_*mes 28
非常接近!
你要
<span data-bind="text: parentProperty().childProperty"> </span>
Run Code Online (Sandbox Code Playgroud)
你的更新小提琴http://jsfiddle.net/szk2e/2/
小智 17
在这里添加答案,因为这最适合我的特殊情况......
有一种情况,蒂姆的答案是行不通的.这是父属性可以的时候undefined.
例如,如果您正在使用itemsSource和selectedItem的公共模式(用户从列表中选择单个项目),则在第一次评估时,以及用户撤消其选择时,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>
Run Code Online (Sandbox Code Playgroud)
请注意,此绑定的行为是(来自文档)
with绑定将动态添加或删除后代元素,具体取决于关联值是否为null/undefined
如果还需要隐藏容器,具体取决于属性是否未定义,则应使用<!-- ko -->虚拟元素围绕容器. 更多信息可以在这里找到.
| 归档时间: |
|
| 查看次数: |
11927 次 |
| 最近记录: |