vee-dom
Version:
Small and easy to use virtual dom library
67 lines (49 loc) • 1.31 kB
JavaScript
'use strict';
const MissingParentException = require('../exceptions/missing-parent');
var uniqueElementIdSequence = 0;
class Element {
constructor(type, attrs, styles) {
this.type = type;
this.attrs = attrs;
this.styles = styles;
this.parentElement = null;
this.htmlElement = null;
this.childElements = [];
this.uniqueElementId = uniqueElementIdSequence++;
}
attach() {
if (this.parentElement === null) {
throw new MissingParentException('No parent element given to this element instance!', this);
}
if (this.attached) {
this.detach();
}
if (this.htmlElement === null) {
this.htmlElement = this._generateHtmlElement();
}
this.childElements.forEach(function(child) {
child.attach();
});
this.parentElement.appendChild(this.htmlElement);
this.attached = true;
}
detach() {
if (this.parentElement === null) {
throw new MissingParentException('No parent element given to this element instance!', this);
}
if (!this.attached) {
return;
}
this.childElements.forEach(function(child) {
child.detach();
});
this.htmlElement.remove();
this.attached = false;
}
_generateHtmlElement() {
let htmlElement = document.createElement(this.type);
// TODO: adding attributes
return htmlElement;
}
}
module.exports = Element;