Created
April 26, 2017 20:26
-
-
Save pomber/b7cd21f45709482b5728b7540f0e98ed to your computer and use it in GitHub Desktop.
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 render(element, parentDom) { | |
const { type, props } = element; | |
// Create DOM element | |
const isTextElement = type === "TEXT ELEMENT"; | |
const dom = isTextElement | |
? document.createTextNode("") | |
: document.createElement(type); | |
// Add event listeners | |
const isListener = name => name.startsWith("on"); | |
Object.keys(props).filter(isListener).forEach(name => { | |
const eventType = name.toLowerCase().substring(2); | |
dom.addEventListener(eventType, props[name]); | |
}); | |
// Set properties | |
const isAttribute = name => !isListener(name) && name != "children"; | |
Object.keys(props).filter(isAttribute).forEach(name => { | |
dom[name] = props[name]; | |
}); | |
// Render children | |
const childElements = props.children || []; | |
childElements.forEach(childElement => render(childElement, dom)); | |
// Append to parent | |
parentDom.appendChild(dom); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment