Meteor: how to create a reactive tree structure from a collection

I use the latest version of the meteor, and this is a local deployment. I have a collection (Folders) that contains a tree structure in which the child nodes have the parent node id as an attribute. I would like to display the tree in the widgets of the user interface tree. I studied recursive template themes, but I find it difficult to find child nodes. Here is the appropriate template and code.

<template name="sideTreeTemplate"> <div id="tree" style="height: 200px"> <h2 class="panel">My Data</h2> <ul id="treeData" style="display: none;"> {{#each treeItems }} {{> treeNodeTemplate}} {{/each }} </ul> </div> </template> <template name="treeNodeTemplate" > <li id="{{id}}" title="{{name}}" class="{{type}}"> {{name}} {{#if hasChildren}} <ul> {{#each children}} {{> treeNodeTemplate}} {{/each}} </ul> {{/if}} </li> </template> 

Client.js Code:

 Template.sideTreeTemplate.treeItems = function() { var items = Folders.find({"parent" : null}); console.log("treeItems length=" + items.count()); items.forEach(function(item){ item.newAtt = "Item"; getChildren(item); }); return items; }; var getChildren = function(parent) { console.log("sidetree.getChildren called"); var items = Folders.find({"parent" : parent._id}); if (items.count() > 0) { parent.hasChildren = true; parent.children = items; console.log( "children count for folder " + parent.name + "=" + items.count() + ", hasChildren=" + parent.hasChildren ); items.forEach(function(item) { getChildren(item); }); } }; 

The top level of the tree displays well and is reactive, but none of them displays, although the getChildren function is called for nodes with children. My suspicion is that server synchronization actually deleted the dynamically added properties (i.e. hasChildren , children ) for each node. In this case, how can I make the reactive tree work? Or maybe this is something wrong with my implementation?

Thanks for the help.

+4
source share
1 answer

A simple way is not to add child objects as properties of the parent object. Use the helper instead:

 Template.treeNodeTemplate.hasChildren = function() { return Folders.find({parent: this._id}).count() > 0; }; Template.treeNodeTemplate.children = function() { return Folders.find({parent: this._id}); }; 
+6
source

Source: https://habr.com/ru/post/1496949/


All Articles