Skip to content

Commit 432fe02

Browse files
committed
Component destroy and remove
1 parent 5ff6e58 commit 432fe02

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

example/config.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ class Counter extends tApp.Component {
4343
}
4444
}
4545
render(props) {
46+
for(let i = 0; i < this.children.length; i++) {
47+
this.children[i].destroy();
48+
}
4649
return (`
4750
<div>
4851
[[

tApp.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -401,10 +401,23 @@ class tApp {
401401
static getComponent(id) {
402402
return tApp.components[id];
403403
}
404+
static removeComponent(id) {
405+
let els = document.querySelectorAll(`[tapp-component="${id}"]`);
406+
for(let i = 0; i < els.length; i++) {
407+
els[i].remove();
408+
}
409+
if(tApp.getComponent(id) == null) {
410+
return false;
411+
} else {
412+
delete tApp.components[id];
413+
return true;
414+
}
415+
}
404416
static updateComponent(component) {
405417
let compiled = tApp.compileComponent(component, component.props, component.parent);
406-
if(document.querySelector(`[tapp-component="${component.id}"]`) != null) {
407-
document.querySelector(`[tapp-component="${component.id}"]`).outerHTML = compiled;
418+
let els = document.querySelectorAll(`[tapp-component="${component.id}"]`);
419+
for(let i = 0; i < els.length; i++) {
420+
els[i].outerHTML = compiled;
408421
}
409422
}
410423
static compileComponent(component, props = {}, parent = "global") {
@@ -838,7 +851,7 @@ tApp.Component = class {
838851
#parent;
839852
#children;
840853
constructor(state, parent = "global") {
841-
this.#id = new Date().toJSON() + "::" + Math.random().toString(36).substr(2) + "::" + Math.random().toString(36).substr(2) + "::" + Math.random().toString(36).substr(2) + "::" + Math.random().toString(36).substr(2);
854+
this.#id = new Date().toJSON() + "::" + Math.random().toString(36).substr(2) + "::" + Math.random().toString(36).substr(2);
842855
if(parent != "") {
843856
if(typeof parent == "string") {
844857
this.#parent = tApp.getComponent(parent);
@@ -870,6 +883,10 @@ tApp.Component = class {
870883
get children() {
871884
return this.#children;
872885
}
886+
clearChildren() {
887+
this.#children = [];
888+
return true;
889+
}
873890
get childrenIds() {
874891
return this.#children.map((child) => {return child.id});
875892
}
@@ -902,6 +919,15 @@ tApp.Component = class {
902919
render(props) {
903920
throw "tAppComponentError: Render method must be overridden.";
904921
}
922+
destroy() {
923+
for(let i = 0; i < this.#children.length; i++) {
924+
this.#children[i].destroy();
925+
}
926+
this.#children = [];
927+
this.#parent = null;
928+
tApp.removeComponent(this.#id);
929+
return true;
930+
}
905931
toString() {
906932
return tApp.compileComponent(this);
907933
}

0 commit comments

Comments
 (0)