tree - Meteor:如何从集合创建响应式(Reactive)树结构

标签 tree meteor

我使用的是最新的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>

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);
    });
  }
};

树的顶层显示良好,并且是 react 性的,但没有显示任何子节点,即使为具有子节点的节点调用了 getChildren 函数也是如此。 我怀疑服务器同步实际上删除了每个节点动态添加的属性(即 hasChildrenchildren)。 在这种情况下,我怎样才能使 react 树发挥作用?或者我的实现可能还有其他问题?

感谢您的帮助。

最佳答案

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

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

Template.treeNodeTemplate.children = function() {
  return Folders.find({parent: this._id});
};

关于tree - Meteor:如何从集合创建响应式(Reactive)树结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18223118/

相关文章:

data-structures - B 树中的最大和最小键数

algorithm - Alpha Beta 搜索和换位表

jquery - 如何在coffeescript中从Template.<template>.events api调用.hover

cordova - Meteor 可以与 PhoneGap 一起使用吗?

Angularjs:ng-options group by

c++ - 使用 C/C++ 将后缀/前缀表达式显示为解析树

checkbox - Vaadin - 如何将复选框组件添加到树中?

javascript - 如何将下拉值传递给模板助手。 [ meteor +火焰]

javascript - meteor 自动成型 : methodserver not called

javascript - Meteor:IronRouter 不会触发 notFound 规则