Skip to content

Instantly share code, notes, and snippets.

@scorredoira
Created October 22, 2020 18:32
Show Gist options
  • Save scorredoira/ea1705d10a8c2b020188550ac350a459 to your computer and use it in GitHub Desktop.
Save scorredoira/ea1705d10a8c2b020188550ac350a459 to your computer and use it in GitHub Desktop.
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