Skip to content

Instantly share code, notes, and snippets.

@edtoken
Last active December 15, 2015 11:43
Show Gist options
  • Select an option

  • Save edtoken/2c27692e86dd4a9f0b5b to your computer and use it in GitHub Desktop.

Select an option

Save edtoken/2c27692e86dd4a9f0b5b to your computer and use it in GitHub Desktop.
var DOMRender = function() {
var self = this;
this.attrs = {};
this.attrs.node = false;
this.attrs.items = false;
this.render = function(items, node) {
var cache = {
renderId: '',
fragment: document.createDocumentFragment(),
node: node
};
function r(list, parent) {
parent.childs = {};
for (var i = 0; i < list.length; i++) {
parent.childs[i] = {};
var item = list[i];
var cache = parent.childs[i];
cache.parent = parent;
item.tagName = item.tagName || 'div';
cache.renderId = parent.renderId + '.' + i;
cache.item = item;
cache.node = document.createElement(item.tagName);
if(item.attrs){
if (item.attrs.className) cache.node.className = item.attrs.className;
if (item.attrs.id) cache.node.id = item.attrs.id;
}
if(item.events){
if (item.events.onClick) cache.node.addEventListener('click', item.events.onClick, false);
}
if(item.text){
cache.node.appendChild(document.createTextNode(item.text));
}
cache.fragment = document.createDocumentFragment();
parent.fragment.appendChild(cache.node);
if (item.childs && item.childs.length) {
r(item.childs, cache);
}
if (i === list.length - 1) {
parent.node.appendChild(parent.fragment);
if (parent.parent) {
parent.parent.fragment.appendChild(parent.node);
}
}
}
}
r(items, cache);
};
return {
render: function(nodeID, items) {
var node = document.getElementById(nodeID);
if (!node || !items || !items.length) {
return false;
}
self.attrs.node = node;
self.attrs.items = items;
self.render(items, self.attrs.node);
}
}
};
var items = [
{
tagName: '',
text: '0',
attrs: {
className: 'asdasdasd',
id: '',
},
events: {
onClick: function() {
alert('click')
}
},
},
{
tagName: '',
text: '1',
attrs: {
className: '',
id: '',
},
childs: [
{
tagName: '',
text: '1.1',
attrs: {
className: '',
id: '',
},
childs: [
{
tagName: '',
text: '1.1.1',
attrs: {
className: '',
id: '',
},
childs: []
}
]
},
{
tagName: '',
text: '1.2',
attrs: {
className: '',
id: '2',
},
childs: [
{
tagName: '',
text: '1.2.1',
attrs: {
className: '',
id: '2',
},
childs: []
}
]
},
{
tagName: '',
text: '1.3',
attrs: {
className: '',
id: '2',
},
childs: []
},
{
tagName: '',
text: '1.4',
attrs: {
className: '',
id: '2',
},
childs: []
}
]
}];
w.render = function() {
var d = new Date();
var count = 1000;
while (count > 0) {
var RItem = new DOMRender();
RItem.render('TEST', items);
count--;
}
console.log(new Date() - d, '.ms');
}
w.render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment