Skip to content

Instantly share code, notes, and snippets.

@pixelass
Created April 29, 2016 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pixelass/0375c1b1ed430c7a60ecfac04f6a5b7f to your computer and use it in GitHub Desktop.
Save pixelass/0375c1b1ed430c7a60ecfac04f6a5b7f to your computer and use it in GitHub Desktop.
virtual DOM helper
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