Knockoutjs Recurring Array

时间:2014-08-29 08:57:13

标签: asp.net knockout.js ko.observablearray

我正在使用KnockoutJS创建一个树视图样式的对象,并且需要能够拥有x个子文件夹和项目。有没有人在屏幕上做过重复阵列,我通常使用foreach,我可以将一个孩子放在另一个孩子中,但我无法弄清楚如何更改模板以使它们反复出现,是否可能?为了澄清我可以将物品放入淘汰赛中,只需将它们显示在屏幕上即可。

在互联网上到处查看但只能找到嵌套模板而不是重复模板。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

让我演示如何使用模板实现此目的。 假设您有以下viewmodel:

var comments = [{
    id: 1,
    comment: 'How can i use knockoutjs?',
    childrenLength: 3,
    children: [{
        id: 2,
        comment: 'Please search before asking',
        childrenLength: 0,
        children: []
    }, {
        id: 3,
        comment: 'Please read the documentation',
        childrenLength: 0,
        children: []
    }, {
        id: 4,
        comment: 'You can see the blog posts on this',
        childrenLength: 2,
        children: [{
            id: 5,
            comment: 'Please search before asking',
            childrenLength: 0,
            children: []
        }, {
            id: 6,
            comment: 'Please search before asking',
            childrenLength: 0,
            children: []
        }]
    }]
}, {
    id: 7,
    comment: 'You question is not sufficient to be asked here?',
    childrenLength: 3,
    children: [{
        id: 8,
        comment: 'Please seach before asking',
        childrenLength: 0,
        children: []
    }, {
        id: 9,
        comment: 'Please read the documentation',
        childrenLength: 0,
        children: []
    }, {
        id: 10,
        comment: 'You can see the blog posts on this',
        childrenLength: 0,
        children: []
    }]
}]

var vm = function(){
    var self = this
    self.comments = ko.observableArray(comments)
}

$('document').ready(function () {
    ko.applyBindings(new vm())
})

你可以看到这里是多级分支。现在你可以通过递归实现这一点。

<div class="body" data-bind="foreach: comments">
    <div data-bind="template: { name: 'childTemplate', data: $data }"></div>
</div>

<script type="text/html" id="childTemplate">
    <span data-bind="text:comment"></span>
    <!-- ko if: $data.childrenLength > 0 -->
        <!-- ko foreach: children -->
            <div data-bind="template: { name: 'childTemplate', data: $data }" style="padding-left:35px;"></div>
        <!-- /ko -->
    <!-- /ko -->
</script>

Fiddle Demo