Created
October 5, 2017 22:40
-
-
Save JosePedroDias/b558005402b41fe2e33fe9439c3fc571 to your computer and use it in GitHub Desktop.
create elements in a snabbdom-like way, without any virtual thingie. small and opinionated.
This file contains 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
function EL(_nodeName, _attrs, _children) { | |
let attrs = {}, children = []; | |
const argLen = arguments.length; | |
if (argLen === 1) { return document.createTextNode(_nodeName); } | |
else if (argLen === 2) { | |
if (_attrs instanceof Array) { children = _attrs; } | |
else if (_attrs instanceof Object) { attrs = _attrs; } | |
else { throw new Error('2nd arg must be either an object (attrs) or an array (children)!'); } | |
} | |
else if (argLen === 3) { attrs = _attrs; children = _children; } | |
else { throw new Error('Wrong number of params!'); } | |
const classes = (_nodeName.indexOf('.') === -1) ? [_nodeName] : _nodeName.split('.'); | |
const nodeName = classes.shift(); | |
const el = document.createElement(nodeName); | |
classes.forEach(cl => el.classList.add(cl)); | |
Object.keys(attrs).forEach(at => { | |
if (at.substring(0, 2) === 'on') { | |
el.addEventListener(at.substring(2), attrs[at]); | |
} else { | |
el.setAttribute(at, attrs[at]); | |
} | |
}); | |
children.forEach(chEl => el.appendChild(typeof chEl === 'string' ? EL(chEl) : chEl)); | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
https://github.com/JosePedroDias/pixelscamp-eth/blob/master/render.js#L199