【问题标题】:Meteor: How to create reactive tree structure from a collectionMeteor:如何从集合中创建反应树结构
【发布时间】:2013-08-14 17:16:34
【问题描述】:

我使用的是最新的流星版本,这是本地部署。 我有一个包含树结构的集合(文件夹),其中子节点具有父节点 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);
    });
  }
};

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

感谢您的帮助。

【问题讨论】:

  • 专业提示:不要在代码中使用制表符,尤其不要在此处粘贴它们。他们可以打破一切。
  • 专业提示:如果要将集合元素作为数组使用,除了find之外,还需要使用fetch,比如:var items = Folders.find({parent: parent._id}).fetch();

标签: tree meteor


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢休伯特。这是有效的!现在我只需要弄清楚如何在反应后保持树状态(打开/关闭节点)。顺便说一句,不使用“TAB”是什么意思?它会破坏什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
相关资源
最近更新 更多