【问题标题】:Knockoutjs Recurring ArrayKnockoutjs 循环数组
【发布时间】:2014-10-23 06:26:21
【问题描述】:

我正在使用 KnockoutJS 创建一个树视图样式的对象,并且需要能够拥有 x 个子文件夹和项目。有没有人在屏幕上做过一个重复的数组,我通常使用 foreach 并且我可以将一个孩子放在另一个孩子中,但我不知道如何更改模板以使它们重复出现,这甚至可能吗?为了澄清,我可以让这些项目进入淘汰赛,它只是让它们显示在屏幕上。

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

【问题讨论】:

  • 可以看例子here
  • 啊,所以不要使用 foreach 而是使用模板!以后在函数中循环遍历这些项目是否容易?
  • 确定你只需要尝试
  • 谢谢,这是我对在 table/div 中使用 foreach 而不是使用模板的误解。我会试一试,你是想把它作为答案还是你认为我应该删除这个问题?
  • 等我回答你

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


【解决方案1】:

让我演示如何使用模板来实现这一点。 假设您有以下视图模型:

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

【讨论】:

    猜你喜欢
    • 2020-11-09
    • 2012-03-22
    • 1970-01-01
    • 2018-12-23
    • 2019-12-09
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 2012-12-15
    相关资源
    最近更新 更多