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>