簡體   English   中英

使用Knockout'foreach'循環遍歷多維數組

[英]Working with Knockout 'foreach' looping through multidimensional array

我有一個多維關聯數組。

this.items = ko.observableArray([
    { name: "name1", viewable: true, children: [
        { name: "name1-1", viewable: true, children: []},
        { name: "name1-2", viewable: false, children: []}
    ] },
    { name: "name2", viewable: false, children: [] },
    { name: "name3", viewable: true, children: [
        { name: "name3-1", viewable: true, children: []},
    ] },
        { name: "name4", viewable: true, children: [] }
]);

目標是遍歷此數組並僅打印出“可查看”設置為true的值。

我使用了一堆if和foreach語句,但代碼開始失控。 這個例子只涵蓋2個級別購買我的數組可以達到5級深度 ,所以這個代碼將成倍增加並且變得非常快速

<ul data-bind="foreach: items">
    <!-- ko if: viewable -->
    <li data-bind="text: name"></li>
        <!-- ko foreach: children -->
            <!-- ko if: viewable -->
            <li data-bind="text: name"></li>
            <!-- /ko -->
        <!-- /ko -->
    <!-- /ko -->
</ul>

那么循環整個數組有更簡單/更好的方法嗎?

JS小提琴鏈接

Underscore.js有一些很好的方法使用數組也許你可以使用flattenfilter從你的結構創建一個數組然后你可以寫一個foreach

或者您可以使用模板封裝if: viewable邏輯並遞歸應用模板:

<script type="text/html" id="template">
  <!-- ko if: viewable -->
    <li data-bind="text: name"></li>    
        <!-- ko template: { name: 'template', foreach: $data.children } -->
        <!-- /ko -->    
  <!-- /ko -->
</script>

<ul data-bind="template: { name: 'template', foreach: items } ">
</ul>

演示JSFiddle。

你需要的是一個模板:

<script type="text/html" id="ItemTemplate">
    <!-- ko if: viewable -->
        <li data-bind="text: name"></li>
        <!-- ko template: { name: 'ItemTemplate', foreach: children } --><!-- /ko -->
    <!-- /ko -->
</script>

然后就是:

<ul data-bind="template: { name: 'ItemTemplate', foreach: items }"></ul>

如果在項目上添加空子數組,則可以使用模板

JSFiddle示例

<ul data-bind="foreach: items">
    <idv data-bind="template: {name: 'mytemp'}" />
</ul>
<div data-bind="stopBinding:true">
    <div id="mytemp">
        <div data-bind="visible :viewable">
            <li data-bind="text: name"></li>
            <div data-bind="foreach: children">
                <div data-bind="template: {name: 'mytemp'}" /></div>
        </div>
    </div>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM