Skip to content

Instantly share code, notes, and snippets.

@takashi
Created March 26, 2014 10:22
Show Gist options
  • Save takashi/9780350 to your computer and use it in GitHub Desktop.
Save takashi/9780350 to your computer and use it in GitHub Desktop.
method missing in JavaScript
var HtmlElem = (function(){
'use strict';
var elemStartStr = "<",
elemGut = '</',
elemEndStr = ' >',
elemOmitedClosingTag = ' />',
idStr = ' id="',
classStr = ' class="',
hrefStr = ' href="',
srcStr = ' src="',
htmlStr = '',
drawingElems = [],
defaultOptions = {
id: null,
class: [],
href: null,
src: null
},
hrefObj = ['a', 'area', 'href'],
srcObj = ['frame', 'img', 'script', 'iframe', 'input'],
noClosingTag = ['br', 'img', 'hr', 'meta', 'input', 'embed', 'area', 'base', 'col', 'keygen', 'link', 'param', 'source'];
var toHtml = function(name, options){
var isAddingHref = checkTagAttribute(name, hrefObj),
isAddingSrc = checkTagAttribute(name, srcObj);
if( checkTagAttribute(name, noClosingTag) ){ // element with no closing tag
htmlStr += elemStartStr + name + addId(options) + addClass(options) +
((isAddingHref) ? hrefStr + options.href + '"' : '') +
((isAddingSrc) ? srcStr + options.src + '"' : '') +
elemOmitedClosingTag;
} else { // element with closing tag
htmlStr += elemStartStr + name + addId(options) + addClass(options) +
((isAddingHref) ? hrefStr + '"' : '') +
((isAddingSrc) ? srcStr + '"' : '') +
elemEndStr;
drawingElems.push(name);
}
};
var checkTagAttribute = function(name, checkObj){
var i = 0,
l = checkObj.length;
for(; i < l; i++){
if(checkObj[i] === name) return true;
}
return false;
};
var addId = function(options){
if(options.id === undefined || options.id === null){
return '';
}
return idStr + options.id + '"';
};
var addClass = function(options){
if(options.class === undefined || options.class.length === 0){
return '';
}
return classStr + options.class.join(' ') + '"';
};
var end = function(){
while(drawingElems.length){
htmlStr += elemGut + drawingElems.pop() + elemEndStr;
}
return htmlStr;
};
var extend = function(deafultObj, obj){
var o = deafultObj;
for(i in o){
if(o.hasOwnProperty(i)){
o[i] = obj[i];
}
}
return o;
};
var returns = {
__noSuchMethod__: function(id, args){
if(args[0] !== undefined){
var options = extend(defaultOptions, args[0]);
toHtml(id, options);
return this;
} else {
toHtml(id, defaultOptions);
return this;
}
},
end: end
};
if( typeof enableMethodMissing === 'function' ){
return enableMethodMissing(returns);
} else {
return returns;
};
}());
HtmlElem.html()
.body()
.div({class: "hoge"})
.img({src: "http://image.hoge.com"}).end(); // <html><body><div class="hoge"><img src="http://image.hoge.com"></div></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment