0

我有评论一个Rails 3 Acts_As_Nested模型,它具有下列字段:1.4.3一个Acts_As_Nested型模型(评论)

  • ID
  • PARENT_ID
  • LFT
  • RGT
  • 内容

使用Rails,很容易呈现一个嵌套列表使用类似.parent.children

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

+0

这甚至可能吗?谢谢 – AnApprentice 2011-02-25 02:41:39

回答

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>