Created
January 17, 2023 20:45
-
-
Save retrohacker/0fe502824971238f5055aa3127a280e7 to your computer and use it in GitHub Desktop.
Frontend framework
This file contains hidden or 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
class Template { | |
constructor(id, mount) { | |
if (id) { | |
this.fragment = document.getElementById(id).content.cloneNode(true); | |
} | |
this.mount = mount; | |
this.eventHandlers = {}; | |
this.children = {}; | |
} | |
async addChild(name, child) { | |
if (this.children[name]) { | |
this.children[name].destroy(); | |
} | |
this.children[name] = child; | |
this.children[name].init(); | |
} | |
init(parentNode) { | |
if (this.mount) { | |
this.mount.innerText = ""; | |
this.mount.appendChild(this.fragment); | |
} | |
} | |
destroy() { | |
this.mount.innerText = ""; | |
for (const child in this.children) { | |
this.children[child].destroy(); | |
} | |
} | |
on(event, handler) { | |
this.eventHandlers[event] = this.eventHandlers[event] || []; | |
this.eventHandlers[event].push(handler); | |
} | |
emit(event, ...args) { | |
if (!this.eventHandlers[event]) { | |
return; | |
} | |
this.eventHandlers[event].forEach((handler) => { | |
handler(...args); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment