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