简体   繁体   中英

Tree like structure with single dimension array

I have single dimension array {1, 2, 3, 4.. } where 4 is child of 3, 3 is child of 2 and so-on. I need to display the elements as tree view structure using knockout js. Is it possible to do it without creating parent-child array structure?

Yes, it's possible. Take a look at this fiddle: http://jsfiddle.net/eF5VL/

The core of the solution is function childrenOf that filters plain array of items and returs only children of specified parent. Note that this function also may be ko.computed if you plain array is observable and the subject to change.

var viewModel = {
    items: [
        { id: 1, parent: 0, name: "item 1" },
        { id: 2, parent: 0, name: "item 2" },
        { id: 3, parent: 2, name: "item 2.1" },
        { id: 4, parent: 2, name: "item 2.2" },
        { id: 5, parent: 0, name: "item 3" },
        { id: 6, parent: 5, name: "item 3.1" },
        { id: 7, parent: 6, name: "item 3.1.1" },
        { id: 8, parent: 0, name: "item 4" }
    ],
    childrenOf: function(parent){
        return ko.utils.arrayFilter(
            viewModel.items,
            function(item){ return item.parent == parent; }
        );
    }
};

ko.applyBindings(viewModel);

Markup:

<script id="tree_item" type="text/html">
    <li><span data-bind="text: name"></span>
        <ul data-bind="template: { name: 'tree_item', foreach: $root.childrenOf(id) }"></ul>
    </li>
</script>

<ul data-bind="template: { name: 'tree_item', foreach: childrenOf(0) }"></ul>

Markup also is clear and simple: just one template for every tree item.

UPDATE:

If you are sure that your items are properly sorted you may use another solution as I had answered here: How to display a json data in a tree model using knockout?

You only should preprocess your items once to define level of nesting for every item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM