0

我有一个 Rails 3 Acts_As_NestedModel for Comments,它有以下字段:

  • ID
  • parent_id
  • 左上角
  • rgt
  • 内容

使用 Rails,很容易使用诸如此类的东西来呈现嵌套的评论列表.parent .children

但现在我想使用 KnockoutJS 通过 jQuery 模板输出嵌套的注释。如何在 jQuery Template + KnockoutJS 中输出嵌套?

4

1 回答 1

0

在 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>
于 2011-02-25T06:05:42.410 回答