我正在尝试执行以下操作:(请参阅jsfiddle中的示例:http://jsfiddle.net/graphicsxp/QJK99/1/)
的javascript:
var originalData = {
id: 1,
name: "Main",
children: [ { id: 2, name: "bob" }, { id: 3, name: "ted" } ],
selectedChild: { id: 2, name: "bob" }
};
var viewModel = ko.mapping.fromJS(originalData);
viewModel.selectChild = function(){
var obj = { id: 9, name: "new" };
viewModel.selectedChild(obj);
}
ko.applyBindings(viewModel);
HTML:
<button data-bind="click: selectChild">click me</button>
<br/>
<span data-bind="text: selectedChild.name"></span>
但不显示selectedChild属性。我究竟做错了什么 ?
[编辑]
我必须在此代码中添加括号:
<span data-bind="text: selectedChild().name"></span>
这很好,但我还必须在映射后添加这行代码:
viewModel.selectedChild = ko.observable(viewModel.children()[0]);
这太烦人了。为什么我需要隐含地将属性设置为可观察?另外,如果我没有给它一个默认值,它将无法正常工作。为什么?
答案 0 :(得分:2)
你应该使selectedChild
成为一个计算的observable,它将返回所选的孩子。添加一个observable,它将跟踪选择的子项。只需跟踪id
(或任何唯一标识孩子的属性)。
var originalData = {
id: 1,
name: "Main",
children: [{
id: 2,
name: "bob"
}, {
id: 3,
name: "ted"
}],
selectedId: 2
};
var viewModel = ko.mapping.fromJS(originalData);
viewModel.selectedChild = ko.computed(function() {
var selectedId = this.selectedId(),
children = this.children();
// get the first child that has the same id as the selectedId
return ko.utils.arrayFirst(children, function(child) {
return child.id() === selectedId;
});
}, viewModel);
然后为了让您更容易显示所选子项,请使用with
绑定有条件地呈现是否选择了有效子项。
<div data-bind="with: selectedChild">
<span data-bind="text: name"></span>
</div>