Skip to content

Instantly share code, notes, and snippets.

@retrohacker
Created January 17, 2023 20:45
Show Gist options
  • Save retrohacker/0fe502824971238f5055aa3127a280e7 to your computer and use it in GitHub Desktop.
Save retrohacker/0fe502824971238f5055aa3127a280e7 to your computer and use it in GitHub Desktop.
Frontend framework
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