Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Last active October 1, 2019 06:21
Show Gist options
  • Save mikaelbr/2592e1788c5a3006327be55324c31df3 to your computer and use it in GitHub Desktop.
Save mikaelbr/2592e1788c5a3006327be55324c31df3 to your computer and use it in GitHub Desktop.
// Check if key starts with `on`. If so, it is an event.
const isEvent = (k, v) => k.startsWith("on") && typeof v === "function";
// Removes `on` prefix to use it as event name
const eventName = k => k.substr(2).toLowerCase();
function attrs(el, props) {
for (let [k, val] of Object.entries(props)) {
// Extend attribute check with special case for events
if (isEvent(k)) {
// Is event. Add event listener with props value as callback
el.addEventListener(eventName(k), val);
} else if (k === "class") {
let classes = Array.isArray(val) ? val : [val];
el.classList.add(...classes);
} else {
el.setAttribute(k, val);
}
}
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment