Last active
June 15, 2016 05:20
-
-
Save adamay000/f03bd3bdd8399eac15cb7b84b3043b15 to your computer and use it in GitHub Desktop.
babel-plugin-mjsxを利用してベタ書きしたhtmlをdocument.createElementで作る
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
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); | |
} |
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
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; |
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
{ | |
"babel": { | |
"presets": [ | |
"es2015" | |
], | |
"plugins": [ | |
"mjsx" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment