Last active
April 3, 2025 20:20
-
-
Save henriquegogo/0fb36f804b57c029ba4a7b19280bc040 to your computer and use it in GitHub Desktop.
Create HTML Elements with arguments and nested children
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
| const ElementCreator = new Proxy({}, { | |
| get: (_, tag) => function(...args) { | |
| const el = Object.assign(document.createElement(tag), ...args); | |
| el.append(...args.filter(arg => arg.constructor !== Object)); | |
| return el; | |
| } | |
| }); | |
| const EventsHandler = (fn, el) => ({ | |
| update: (newElement) => el.replaceWith(fn(newElement)), | |
| listen: (ev, fn) => (el.dataset.event = "", el) | |
| .addEventListener(ev, ({detail}) => fn(detail)), | |
| dispatch: (ev, detail) => document.querySelectorAll("[data-event]") | |
| .forEach(el => el.dispatchEvent(new CustomEvent(ev, {detail}))) | |
| }); | |
| const HelloWorld = (message = 'Hello World!') => { | |
| const { div, h1 } = ElementCreator; | |
| const el = | |
| div({ | |
| className: 'hello-world', | |
| onclick: () => dispatch('newdata', 'Bye bye') | |
| }, | |
| h1(message)); | |
| const { update, listen, dispatch } = EventsHandler(HelloWorld, el); | |
| listen('newdata', newMsg => update(newMsg)); | |
| listen('newdata', () => console.log('gotcha!')); | |
| return el; | |
| } | |
| document.body.append(HelloWorld()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment