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 ElementBuilder = new Proxy({}, { get: (_, tagName) => (...args) => { | |
const element = Object.assign(document.createElement(tagName), ...args); | |
element.append(...args.filter(arg => arg.constructor !== Object)); | |
return element; | |
}}); | |
const EventHandler = (element, fn) => Object.assign(element || {}, { | |
update: (...newProps) => element.replaceWith(fn(...newProps)), | |
listen: (eventType, handler) => (element.dataset.event = "", element) | |
.addEventListener(eventType, ({ detail }) => handler(detail)), | |
dispatch: (eventType, detail) => document.querySelectorAll("[data-event]") | |
.forEach(el => el.dispatchEvent(new CustomEvent(eventType, { detail }))) | |
}); | |
const { div, h1, button } = ElementBuilder; | |
function HelloWorld(message = 'Hello World!', buttonLabel = 'Click me!') { | |
const handleEvents = (element) => { | |
const { listen, update } = EventHandler(element, HelloWorld); | |
listen('newdata', update); | |
listen('newdata', () => console.log('gotcha!')); | |
return element; | |
}; | |
return { update, dispatch } = handleEvents( | |
div( | |
h1({ onclick: () => update('Bye bye') }, message), | |
button({ onclick: () => dispatch('newdata', 'Clicked') }, buttonLabel) | |
) | |
); | |
} | |
document.body.append(HelloWorld()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment