Knockoutjs Recurring Array

后端 未结 1 1039
北恋
北恋 2021-01-25 08:23

I am creating a treeview styled object using KnockoutJS and need to be able to have x number of children folders and items. Has anyone done a recurring array on screen, I usual

1条回答
  •  迷失自我
    2021-01-25 08:47

    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.

    Fiddle Demo

    0 讨论(0)
提交回复
热议问题