Last active
August 29, 2015 14:01
-
-
Save dhigginbotham/a29b6a568aea23631e65 to your computer and use it in GitHub Desktop.
make an html element with pojo
This file contains hidden or 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
(function (root, doc) { | |
// var schema = { | |
// target: 'elementalTarget', | |
// method: 'append', | |
// type: 'div', | |
// className: 'elemental-default', | |
// data: { | |
// elemental: 'div' | |
// }, | |
// attrs: { | |
// id: 'elementalDefault', | |
// type: 'content' | |
// } | |
// }; | |
function Elemental(schema) { | |
var dom, el; | |
var opts = {}; | |
var defaults = { | |
target: 'file-elemental-js', | |
method: 'append', | |
type: 'div', | |
className: 'elemental-default', | |
data: {}, | |
attrs: { | |
id: 'elementalDefault' | |
}, | |
child: 'Elements! Whoa!' | |
}; | |
(function() { | |
extend(opts, (schema ? schema : defaults)); | |
dom = doc.createElement(opts.type); | |
el = doc.getElementById(opts.target); | |
domBuilder(function() { | |
insertIntoPage(opts.method); | |
}); | |
}()); | |
function domBuilder(fn) { | |
if (opts.className) dom.className = opts.className; | |
if (opts.data) parseDataAttrs(opts.data); | |
if (opts.attrs) parseAttributes(opts.attrs); | |
if (opts.child) parseChild(opts.child); | |
fn(); | |
}; | |
function insertIntoPage(method) { | |
if (el) { | |
switch (method) { | |
case 'append': | |
el.appendChild(dom); | |
break; | |
case 'replace': | |
el.parentNode.replaceChild(dom, el); | |
break; | |
} | |
} | |
}; | |
function parseDataAttrs(data) { | |
for (var key in data) { | |
dom.setAttribute('data-' + key, data[key]); | |
} | |
}; | |
function parseAttributes(attrs) { | |
for (var key in attrs) { | |
dom.setAttribute(key, attrs[key]); | |
} | |
}; | |
function parseChild(child) { | |
if (typeof child == 'string') { | |
parseText(child); | |
} else { | |
Elemental(child); | |
} | |
}; | |
function parseText(text) { | |
var text = doc.createTextNode(text); | |
dom.appendChild(text); | |
}; | |
}; | |
function extend(dest) { | |
var args = Array.prototype.slice.call(arguments, 1); | |
var ln = args.length; | |
for (var i=0;i<ln;++i) { | |
for (var o in args[i]) { | |
dest[o] = args[i][o]; | |
} | |
}; | |
return dest; | |
}; | |
if (typeof module != 'undefined' && module.exports) { | |
module.exports = Elemental; | |
} else { | |
root.Elemental = Elemental; | |
} | |
}(window, document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment