浏览代码

前端树结构

MaiXinRong 7 年之前
父节点
当前提交
446d35580b
共有 1 个文件被更改,包括 48 次插入0 次删除
  1. 48 0
      app/public/js/path_tree.js

+ 48 - 0
app/public/js/path_tree.js

@@ -0,0 +1,48 @@
+
+const createNewPathTree = function (setting) {
+    const treeSetting = JSON.parse(JSON.stringify(setting));
+    const itemsPre = 'id_';
+
+    const PathTree = function () {
+        // 以key为索引
+        this.items = {};
+        // 以排序为索引
+        this.nodes = [];
+    };
+    const proto = PathTree.prototype;
+    proto.sortTreeNode = function () {
+        this.nodes.sort(function (a, b) {
+            return a.level === b.level ? a.order - b.order : a.level - b.level;
+        });
+    };
+    proto.loadDatas = function (datas) {
+        for (const data of datas) {
+            const keyName = itemsPre + data[treeSetting.id];
+            this.items[keyName] = JSON.parse(JSON.stringify(data));
+            this.nodes.push(this.items[keyName]);
+        }
+        this.sortTreeNode();
+        for (const node of this.nodes) {
+            const children = this.getChildren(node);
+            node.expanded = children.length > 0;
+        }
+    };
+    proto.getItems = function (id) {
+        return this.items[itemsPre + id];
+    };
+    proto.getParent = function (node) {
+        return this.getItems(node[treeSetting.pid]);
+    };
+    proto.getChildren = function (node) {
+        const pid = node ? node[treeSetting.id] : treeSetting.rootId;
+        return this.nodes.filter(function (x) {
+            return x[treeSetting.pid] === pid;
+        });
+    };
+    proto.isLastSibling = function (node) {
+        const siblings = this.getChildren(this.getParent(node));
+        return node.order === siblings.length;
+    };
+
+    return new PathTree();
+}