Knockoutjs Recurring Array

耗尽温柔 提交于 2019-12-02 08:22:43
Muhammad Raheel

Let me demonstrate how you can achieve this using a template. Let suppose you have the following 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())
})

You can see here is multilevel branching. Now you can achieve this with recursion.

<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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!