path_tree.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const createNewPathTree = function (setting) {
  2. const treeSetting = JSON.parse(JSON.stringify(setting));
  3. const itemsPre = 'id_';
  4. const PathTree = function () {
  5. // 以key为索引
  6. this.items = {};
  7. // 以排序为索引
  8. this.nodes = [];
  9. };
  10. const proto = PathTree.prototype;
  11. proto.sortTreeNode = function () {
  12. this.nodes.sort(function (a, b) {
  13. return a.level === b.level ? a.order - b.order : a.level - b.level;
  14. });
  15. };
  16. proto.loadDatas = function (datas) {
  17. for (const data of datas) {
  18. const keyName = itemsPre + data[treeSetting.id];
  19. this.items[keyName] = JSON.parse(JSON.stringify(data));
  20. this.nodes.push(this.items[keyName]);
  21. }
  22. this.sortTreeNode();
  23. for (const node of this.nodes) {
  24. const children = this.getChildren(node);
  25. node.expanded = children.length > 0;
  26. }
  27. };
  28. proto.getItems = function (id) {
  29. return this.items[itemsPre + id];
  30. };
  31. proto.getParent = function (node) {
  32. return this.getItems(node[treeSetting.pid]);
  33. };
  34. proto.getChildren = function (node) {
  35. const pid = node ? node[treeSetting.id] : treeSetting.rootId;
  36. return this.nodes.filter(function (x) {
  37. return x[treeSetting.pid] === pid;
  38. });
  39. };
  40. proto.isLastSibling = function (node) {
  41. const siblings = this.getChildren(this.getParent(node));
  42. return node.order === siblings.length;
  43. };
  44. return new PathTree();
  45. }