Skip to content

Instantly share code, notes, and snippets.

@kirjavascript
Last active May 4, 2020 16:13
Show Gist options
  • Save kirjavascript/a42856892961c790a41788692f1a8460 to your computer and use it in GitHub Desktop.
Save kirjavascript/a42856892961c790a41788692f1a8460 to your computer and use it in GitHub Desktop.
function h(tag, attrs = {}, children = []) {
const node = document.createElement(tag);
node.__children = children;
Object.entries(attrs).forEach(([k, v]) => {
/^on/.test(k)
? node.addEventListener(k.slice(2), v)
: node.setAttribute(k, v);
});
return node;
}
function render(node, tree) {
while(node.firstChild) node.removeChild(node.lastChild);
(function recurse(node, items) {
items.forEach((el) => {
node.appendChild(typeof el !== 'object'
? new Text(el) : recurse(el, el.__children))
});
return node;
})(node, tree);
}
// userland
let value = 23;
render(document.body.appendChild(h('div')), [
h('input', {
type: 'range',
value,
oninput: (e) => {
value = e.target.value;
update();
}}),
]);
const data = document.body.appendChild(h('div'));
function update() {
render(data, [
value
]);
}
update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment