我正在尝试在嵌套元素中动态添加数据,问题是我想将从服务器返回的每个对象转换为可观察数组。
function viewModel() {
this.projects = ko.observableArray();
this.addMember = function addMember() {
var match = ko.utils.arrayFirst(this.projects(), function (item) {
// return the first item in the array just for simulation
return true;
});
if (match) {
var newItem = {
name: 'member 5'
};
match.members.push(newItem);
}
};
}
var vm = new viewModel();
// manually declare observable
vm.projects.push({
name: ko.observable('project a'),
members: ko.observableArray([
{ name: 'member 1' },
{ name: 'member 2' }
])
});
vm.projects.push({
name: ko.observable('project b'),
members: ko.observableArray([
{ name: 'member 3' },
{ name: 'member 4' }
])
});
ko.applyBindings(vm);
这就是我现在得到的:
在此示例中,我想将 ko.mapping 用于“将所有设置对象作为数组的列表”而不将每个对象创建为 observablearray