Skip to content

Instantly share code, notes, and snippets.

@gtindo
Created November 18, 2024 22:18
Show Gist options
  • Save gtindo/19f1d9b431c8c2704aa7b0b38084b2d6 to your computer and use it in GitHub Desktop.
Save gtindo/19f1d9b431c8c2704aa7b0b38084b2d6 to your computer and use it in GitHub Desktop.
Web components utils
function createReactive(initialValue, sideEffect) {
const proxy = new Proxy(
{ value: initialValue },
{
set(target, prop, newValue) {
const outcome = Reflect.set(...arguments);
if (outcome) sideEffect(newValue);
return outcome;
},
get(target, prop, receiver) {
return Reflect.get(...arguments);
},
}
);
return proxy;
}
/**
* @param {HTMLElement} element
* @param {string} id
*/
function attachTemplate(element, id) {
const template = document.getElementById(id);
element.attachShadow({ mode: 'open' });
element.shadowRoot.appendChild(template.content.cloneNode(true));
}
/**
* @param {ShadowRoot} root
* @param {Array<string>} targets
* @returns {Record<string, HTMLElement>}
*/
function getTargetElements(root, targets) {
const elements = {};
targets.forEach(
(target) =>
(elements[target] = root.querySelector(`[data-target="${target}"]`))
);
return elements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment