Created
April 29, 2016 16:45
-
-
Save pixelass/0375c1b1ed430c7a60ecfac04f6a5b7f to your computer and use it in GitHub Desktop.
virtual DOM helper
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
const DOMestic = (tpl) => { | |
const attach = parent => { | |
if (typeof parent !== 'object' || !parent.hasOwnProperty('el')) { | |
return console.error('parent should be an object with the property \'el\''); | |
} | |
let children = Array.from(parent.el.children); | |
let keys = []; | |
children.forEach((el, index) => { | |
let key = el.getAttribute('key'); | |
el.removeAttribute('key'); | |
if (typeof key === 'undefined' || key === null || keys.indexOf(key) >= 0) { | |
return console.error('each sibling requires a unique key', key, el); | |
} | |
keys.push(key); | |
let child = { | |
el | |
}; | |
parent[key] = child | |
if (el.childElementCount > 0) { | |
attach(child); | |
} | |
}); | |
return parent; | |
} | |
let wrapper = document.createElement('div'); | |
wrapper.innerHTML = tpl; | |
let template = wrapper.firstElementChild; | |
let vDOM = { | |
el: template, | |
appendTo: target => target.appendChild(template) | |
}; | |
return attach(vDOM); | |
} | |
export default DOMestic; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment