一、jsfiddle链接http://jsfiddle.net/wenbert/m5pHs/36/
<button data-bind="click: addHero">Add Hero With Meta</button>
<ul data-bind="foreach: heroes">
<li class="parent" data-bind="ifnot: isDeleted">
<input class="big-box" type="text" data-bind="value: name" />
<button class="btn-small" data-bind="click: $parent.removeHero">Remove Hero</button>
<br/>
<button class="btn-small" data-bind="click: $parent.addMeta">Add Meta</button>
<div class="child" data-bind="template: { name: 'checkbox-template' }"></div>
</li>
</ul>
<script type="text/html" id="checkbox-template">
<ul data-bind="foreach: meta">
<li data-bind="ifnot: isDeleted">
<input class="child-item blue" type="text" data-bind="value: name" />:
<input class="child-item small" type="text" data-bind="value: damage" />
<button class="btn-small" data-bind="click: $parent.removeMeta">Remove Meta</button>
<br/>
</li>
</ul>
</script>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
Javascript
var initialData = [
{
name: "Batman",
isDelete: false,
meta: [
{ name: "Belt", damage: "99", isDeleted: false },
{ name: "Gun", damage: "104", isDeleted: false}
]
},
{
name: "Hulk",
isDelete: false,
meta: [
{ name: "Pants", damage: "1", isDeleted: false }
]
},
];
function Hero(data) {
var self = this;
self.name = ko.observable(data.name);
self.meta = ko.observableArray(data.meta);
self.isDeleted = ko.observable(data.isDeleted);
}
function Meta(data) {
var self = this;
self.name= ko.observable(data.name);
self.damage= ko.observable(data.damage);
self.isDeleted = ko.observable(data.isDeleted);
}
function SuperheroViewModel() {
var self = this;
self.heroes = ko.observableArray();
self.heroes.meta = ko.observableArray();
self.heroes.push(new Hero(initialData[0]));
self.heroes.push(new Hero(initialData[1]));
self.addHero = function() {
self.heroes.push(
new Hero({
name: 'Wolverine',
isDelete: false,
meta: [new Meta({name: 'Claws', damage: '200', isDeleted: false})]
})
);
/*
//Using something like this also does not enable me to update the child items when adding.
self.heroes.push(new Hero(initialData[1])
);*/
}
self.addMeta = function(item) {
item.meta.push(new Meta({name: '--', damage: '0', isDeleted: false}));
}
self.removeHero= function(item) {
item.isDeleted(true);
}
self.removeMeta = function(item) {
item.isDeleted(true);
}
}
ko.applyBindings(new SuperheroViewModel());
<strong>长什么样子
什么有效:
- 添加英雄
- 移除英雄(通过设置
isDeleted
为 true) - 添加元
- 更新英雄名称会更新调试视图中的数据
什么不起作用:
- 删除 Meta - 我无法将其设置
meta.isDeleted
为 true - Meta (EG: Belt, Gun, Pants),当您更改文本框中的值时不会更新。但是,如果您编辑 Meta,然后编辑父级,则 Meta 会更新。看起来只有在更新父项时才会触发子项。
明白了
- 如果您添加了一个新英雄然后编辑了 Meta,即使没有更新父项,它们也会自动更新。
所以2个问题:
- 如何使用我的 jsfiddle 中的内容设置子对象的值?http://jsfiddle.net/wenbert/m5pHs/36/
- 子项更新时如何触发更新?现在,子项更新仅在您同时更新父项时触发(例如:蝙蝠侠、绿巨人)
更新:似乎子项没有更新,因为它们是使用initialData array
.
谢谢!