Created
October 22, 2020 18:32
-
-
Save scorredoira/ea1705d10a8c2b020188550ac350a459 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Control { | |
readonly element: HTMLElement | |
protected children: Control[] | |
private _parent: Control; | |
constructor(element: string | HTMLElement, className?: string, parent?: Control, content?: string | Control) { | |
if (typeof element === "string") { | |
element = document.createElement(element) | |
} | |
this.element = element | |
this.children = [] | |
if (className) { | |
element.classList.add(className) | |
} | |
if (parent) { | |
parent.appendChild(this) | |
} | |
if (content !== undefined && content != null) { | |
if (typeof content === "string") { | |
S.setText(this.element, content, true) | |
} else { | |
this.appendChild(content) | |
} | |
} | |
} | |
public get parent(): Control { | |
return this._parent; | |
} | |
protected setParent(v: Control) { | |
if (this._parent) { | |
this._parent.removeChild(this) | |
} | |
this._parent = v | |
} | |
getChildren() { | |
return this.children as ReadonlyArray<Control> | |
} | |
removeChild(control: Control) { | |
this.children.remove(control) | |
control.element.remove() | |
} | |
replaceChild(control: Control, old?: Control) { | |
S.replace(control.element, old.element) | |
this.children.remove(old) | |
control.setParent(this) | |
this.children.push(control) | |
} | |
appendChild(control: Control) { | |
control.setParent(this) | |
this.children.push(control) | |
this.element.appendChild(control.element) | |
} | |
clear() { | |
for (let c of this.children) { | |
c.clear() | |
c.remove() | |
} | |
this.children = [] | |
this.element.innerHTML = "" | |
} | |
remove() { | |
if (this.parent) { | |
this.parent.removeChild(this) | |
} else { | |
this.element.remove() | |
} | |
} | |
dispatchEvent(event: Event) { | |
this.element.dispatchEvent(event) | |
} | |
addEventListener(type: string, listener: (this: HTMLInputElement, ev: Event) => any, options?: boolean | AddEventListenerOptions) { | |
this.element.addEventListener(type, listener, options) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment