yyzone
Version:
yyzone vue components and utils
109 lines (92 loc) • 2.96 kB
JavaScript
let idIndex = 0;
export class Node {
constructor(options) {
this.id = idIndex++;
this.checked = false;
this.expanded = false;
this.data = null;
this.parent = null;
this.draggingInner = false;
this.label = '';
this.key = this.id;
this.children = [];
this.loaded = false;
this.isLeaf = false;
this.level = 0;
for (let prop in options) {
if (options.hasOwnProperty(prop)) {
this[prop] = options[prop]
}
}
const config = this.__config__;
if (config) {
this.lazy = config.lazy;
const props = config.props;
if (props && typeof props.isLeaf !== "undefined") {
this.isLeafByUser = typeof props.isLeaf === 'function' ? props.isLeaf(this.data) : props.isLeaf;
} else if (this.lazy && config.defaultExpandAll) {
this.isLeaf = true
}
}
this.loaded = false;
this.loading = false;
if (this.parent) {
this.level = this.parent.level + 1;
}
}
resetDragState() {
this.draggingInner = false;
}
updateLeafState() {
if (this.lazy === true && this.loaded !== true && typeof this.isLeafByUser !== 'undefined') {
return this.isLeaf = this.isLeafByUser;
}
if (!this.lazy || (this.lazy && this.loaded)) {
return this.isLeaf = !(this.children && this.children.length);
}
this.leaf = false;
}
setChildrenData(data = []) {
if (!data) return
const _this = this;
const props = this.__config__.props;
this.children = data.map(child => {
const childNode = new Node({
data: child,
label: child[props.label],
key: child[_this.__config__.nodeKey],
parent: _this,
__config__: _this.__config__
})
if (child[props.children]) {
childNode.setChildrenData(child[props.children])
}
return childNode;
})
}
insertPrev(node) {
this.parent.children.splice(this.getIndexOfParnet(), 0, node);
node.parent = this.parent;
this.updateLeafState();
this.parent.updateLeafState();
}
insertNext(node) {
this.parent.children.splice(this.getIndexOfParnet() + 1, 0, node);
node.parent = this.parent;
this.updateLeafState();
this.parent.updateLeafState();
}
insertInner(node) {
this.children.unshift(node);
node.parent = this;
this.updateLeafState();
this.parent.updateLeafState();
}
getIndexOfParnet() {
for (let i in this.parent.children) {
if (this.parent.children[i] === this) {
return i;
}
}
}
}