用淘汰赛创造不确定深度的树木

时间:2014-08-13 22:42:09

标签: knockout.js

我正在使用knockout创建一个带注释的简单博客系统。评论树可能是一个不确定的级别,但我不知道如何用淘汰赛做到这一点。这是对象结构:

var BlogEntry = function(entry) {
    var self = this;

    self.author = ko.observable(entry.Author);
    self.submitted = ko.observable(entry.Submitted);
    self.comments = ko.observableArray();        
    for(var commentIndex in entry.Comments) {
        self.comments.push(new BlogComment(entry[commentIndex]));
    }
}

var BlogComment = function(comment) {
    var self = this;

    self.author = ko.observable(comment.Author);
    self.submitted = ko.observable(comment.Submitted);
    self.comments = ko.observableArray();
    for(var subCommentIndex in comment.Comments) {
        self.comments.push(new BlogComment(comment[subCommentIndex]));
    }
}

我想要这样的事情:

<div id="BlogEntries" data-bind="foreach: comments">
    <div class="blog-entry">
        <div data-bind="text: author() + " - " + submitted()"></div>
        <div data-bind="foreach: comments">
            <div class="comment">
                <div data-bind="text: author() + " - " + submitted()"></div>
                <div data-bind="foreach: comments">
                    <!-- Would need infinite markup here -->
                </div>
            </div>
        </div>
    </div>
</div>

如果不设置任意最大注释树深度并写出每个可能的级别,我该怎么做?

1 个答案:

答案 0 :(得分:2)

简单。 Templates可以递归使用。尝试这样的事情。

<script type="text/html" id="comment">
    <div class="comment">
        <!-- more comment specific stuff here -->
        <div data-bind="text: author() + ' - ' + submitted()"></div>
        <div class="comments" data-bind="template: {name: 'comment', foreach: comments}"></div>
    </div>
</script>

<div id="BlogEntries" data-bind="foreach: blogEntries">
    <div class="blog-entry">
        <!-- more blog-entry specific stuff here -->
        <div data-bind="text: author() + ' - ' + submitted()"></div>
        <div class="comments" data-bind="template: {name: 'comment', foreach: comments}"></div>
    </div>
</div>

提示:尽量避免在视图中进行计算(如author() + ' - ' + submitted());这会使您的视图与视图模型的结构更紧密地绑定。它增加了视觉上的混乱。

更好:创建一个computed,返回一个组合值,或者将数据分布在不同的元素上并进行适当的排列。

http://jsfiddle.net/3ne16rex/