Skip to content

Instantly share code, notes, and snippets.

@adamay000
Last active June 15, 2016 05:20
Show Gist options
  • Save adamay000/f03bd3bdd8399eac15cb7b84b3043b15 to your computer and use it in GitHub Desktop.
Save adamay000/f03bd3bdd8399eac15cb7b84b3043b15 to your computer and use it in GitHub Desktop.
babel-plugin-mjsxを利用してベタ書きしたhtmlをdocument.createElementで作る
import DomRenderer from './DomRenderer.js';
const title = 'title';
document.body.appendChild(DomRenderer.render(
<dummy>
<h1>{title}</h1>
<button callback={onClick}>button</button>
</dummy>
));
function onClick($dom) {
$dom.addEventListener('click', () => {
console.log('clicked');
}, false);
}
class DomRenderer {
static render(arg1, arg2) {
if (arg2) {
const $dom = DomRenderer.createDom(arg2);
arg1.parentNode.replaceChild($dom, arg1);
return $dom;
}
return DomRenderer.createDom(arg1);
}
static createDom(domData) {
if (typeof domData === 'string') {
return document.createTextNode(domData);
}
if (domData.length) {
const $fragment = document.createDocumentFragment();
domData.forEach(child => {
$fragment.appendChild(DomRenderer.render(child));
});
return $fragment;
}
const $dom = (!domData.tag || domData.tag === 'dummy') ? document.createDocumentFragment() : document.createElement(domData.tag);
domData.attrs && Object.keys(domData.attrs).forEach(attrName => {
if (attrName === 'className') {
$dom.className = domData.attrs.className;
return;
}
if (attrName === 'style') {
const value = domData.attrs.style;
if (typeof value === 'object') {
Object.keys(value).forEach(property => {
$dom.style[property] = value[property];
});
return;
}
$dom.style.cssText = value;
return;
}
if (attrName === 'callback') {
domData.attrs.callback($dom);
return;
}
$dom.setAttribute(attrName, domData.attrs[attrName]);
});
domData.children && domData.children.forEach(child => {
$dom.appendChild(DomRenderer.render(child));
});
return $dom;
}
}
export default DomRenderer;
{
"babel": {
"presets": [
"es2015"
],
"plugins": [
"mjsx"
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment