我正在尝试一个淘汰赛映射样本,并认为我快到了。我似乎无法向 viewModel.foos 添加新的 Foo - 任何人都可以看到我在这里错过了什么吗?
var Foo = function (data) {
var self = this;
self.id = data.id;
self.Name = ko.observable(data.Name);
}
var dataMappingOptions = {
key: function(data) {
return data.id;
},
create: function (options) {
return new Foo(options.data);
}
};
var viewModel = {
foos: ko.mapping.fromJS([]),
loadInitialData: function () {
ko.mapping.fromJS(serverData, dataMappingOptions, viewModel.foos);
},
loadUpdatedData: function () {
ko.mapping.fromJS(serverData, dataMappingOptions, viewModel.foos);
}
};
viewModel.addFoo = function () {
viewModel.foos.push(ko.mapping.fromJS(new Foo()));
viewModel.loadUpdatedData();
}
<ul data-bind="template: {name: 'TopTemplate'}"></ul>
<script type="text/html" id="TopTemplate">
<li><span>Result</span>
<ul data-bind=" template: {name: 'FooTemplate' , foreach: foos} " style="list-style-type:circle;margin-left:15px">
</ul>
</li>
<button data-bind='click: addFoo'>Add Foo</button>
</script>
<script type="text/html" id="FooTemplate">
<li><span data-bind='text: Name'></span>
</li>
</script>