發表在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