发表在KO论坛上,但在这里也添加了,因为问题在这里。
这样做的一个好方法是递归调用模板。如果您的结构是嵌套的,那么您可以每次将这些孩子传递给模板。如果你的结构是平的,那么你需要过滤传递给模板的项目。
样品在这里:http://jsfiddle.net/rniemeyer/Xydth/
对于扁平结构,它可能看起来像:
<ul data-bind="template: { name: 'comment', foreach: viewModel.getChildren(0) }"></ul>
<script id="comment" type="text/html">
<li>
<span data-bind="text: content"></span>
<ul data-bind="template: { name: 'comment', foreach: viewModel.getChildren($data.id) }"></ul>
</li>
</script>
<script type="text/javascript">
function comment(id, parentId, content) {
this.id = id;
this.parentId = parentId;
this.content = ko.observable(content);
}
var viewModel = {
comments: ko.observableArray([
new comment(1, 0, "one content"),
new comment(2, 1, "two content"),
new comment(3, 0, "three content"),
new comment(4, 0, "four content"),
new comment(5, 4, "five content"),
new comment(6, 4, "six content"),
new comment(7, 6, "secent content"),
new comment(8, 0, "eight content")
]),
getChildren: function(parentId) {
return ko.utils.arrayFilter(this.comments(), function(comment) {
return comment.parentId == parentId;
});
}
};
ko.applyBindings(viewModel);
</script>
这甚至可能吗?谢谢 – AnApprentice 2011-02-25 02:41:39