Meteor:如何从集合中创建活动树结构

use*_*514 4 tree meteor

我使用的是最新的流星版本,这是本地部署.我有一个包含树结构的集合(文件夹),其中子节点具有父节点id作为属性.我想在UI树小部件中显示树.我已经研究了递归模板主题,但是,我很难显示子节点.以下是相关的模板和代码.

<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>
Run Code Online (Sandbox Code Playgroud)

client.js代码:

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);
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

树的顶层显示正常,并且是反应性的,但是没有显示任何子getChildren节点,即使为具有子节点的节点调用该函数.我的怀疑是服务器同步实际删除动态添加特性(即hasChildren,children对于每个节点).在这种情况下,如何使反应树工作?或者我的实现可能还有其他问题?

谢谢您的帮助.

Hub*_* OG 7

简单的方法是不将子对象添加为父对象的属性.相反,使用帮助器:

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

Template.treeNodeTemplate.children = function() {
  return Folders.find({parent: this._id});
};
Run Code Online (Sandbox Code Playgroud)