给定嵌套类别的模型和视图模型:
function Category(id, name) {
var self = this;
self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000');
self.Name = ko.observable(name);
self.children = ko.observableArray();
self.addCategory = function () {
self.children.push(new Category("", ""));
};
self.removeCategory = function(category) {
self.children.remove(category);
};
}
var CategoryManagerViewModel = function() {
var self = this;
self.children = ko.observableArray();
self.addCategory = function () {
self.children.push(new Category("", ""));
};
self.removeCategory = function (category) {
self.children.remove(category);
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.children), null, 2));
};
self.lastSavedJson = ko.observable("");
};
我如何制作模板,以使更多的子类别被嵌套(然后嵌套在这些类别中等)。模板继续被重复使用以反映这一点?
目前我的模板是:
<table class='categoriesEditor'>
<tr>
<th>Category</th>
<th>Children</th>
</tr>
<tbody data-bind="foreach: children">
<tr>
<td>
<input data-bind='value: Name' />
<div><a href='#' style="color:black" data-bind='click: removeCategory'>Delete</a></div>
</td>
<td>
<table>
<tbody data-bind="foreach: children">
<tr>
<td><input data-bind='value: Name' /></td>
<td><a href='#' style="color:black" data-bind='click: removeCategory'>Delete</a></td>
<td>
<table>
<tbody data-bind="foreach: children">
<tr>
<td><input data-bind='value: Name' /></td>
<td><a href='#' style="color:black" data-bind='click: removeCategory'>Delete</a></td>
</tr>
</tbody>
</table>
<a href='#' style="color:black" data-bind='click: addCategory'>Add cat</a>
</td>
</tr>
</tbody>
</table>
<a href='#' style="color:black" data-bind='click: addCategory'>Add cat</a>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<button data-bind='click: addCategory'>Add root category</button>
<button data-bind='click: save, enable: children().length > 0'>Save to JSON</button>
</p>
这使我可以在类别中进行3个层次的嵌套,这对这个应用程序来说是可以的,但是如果我想要更多呢?我会为此复制粘贴吗?肯定不是,我认为我已经完成了。
更新:
绑定如下:
var viewModel = new CategoryManagerViewModel();
viewModel.addCategory();
ko.applyBindings(viewModel);
对于这样的方案,您需要使用可以递归调用的命名模板。因此,您将拥有一个设置(简化),例如:
<table>
<tbody data-bind="template: { name: 'itemTmpl', data: root }"></tbody>
</table>
<script id="itemTmpl" type="text/html">
<tr>
<td data-bind="text: name"></td>
<td>
<table>
<tbody data-bind="template: { name: 'itemTmpl', foreach: children }"></tbody>
</table>
</td>
</tr>
</script>
因此,您可以在根笔记上调用模板,然后从那里调用它在孩子身上称为(将其称为孩子等)
)示例在这里:http://jsfiddle.net/rniemeyer/ex3xt/