Created
March 2, 2009 12:49
-
-
Save danwrong/72734 to your computer and use it in GitHub Desktop.
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
// DOM Builder plugin idea for jQuery | |
// | |
// Usage: | |
// $.build(function(html) { | |
// html.div({ id: 'test' }, html.strong('Some text')); | |
// }); => DOM fragment | |
// | |
(function($) { | |
flatten = function(arr) { | |
var res = []; | |
for (var i=0; i < arr.length; i++) { | |
var item = arr[i]; | |
res = res.concat((item instanceof Array) ? flatten(item) : [item]); | |
} | |
return res; | |
}; | |
HTMLBuilder = function() { | |
this.parts = []; | |
} | |
HTMLBuilder.functionFor = function(element) { | |
return function() { | |
var attrs, children; | |
if (arguments.length > 0) { | |
if (arguments[0].constructor == Object) { | |
attrs = arguments[0]; | |
children = Array.prototype.slice.call(arguments, 1); | |
} else { | |
children = flatten(arguments); | |
}; | |
} | |
return this.build(element, attrs, children); | |
} | |
} | |
HTMLBuilder.prototype = { | |
attributes: function(attrs) { | |
var pairs = []; | |
for (var key in attrs) { | |
pairs.push([key, '="', attrs[key], '"'].join('')); | |
} | |
if (pairs.length == 0) return ''; | |
else return (' ' + pairs.join(' ')); | |
}, | |
selfClosingTag: function(name, attrs) { | |
return ['<', name, this.attributes(attrs), ' />']; | |
}, | |
openingTag: function(name, attrs) { | |
return ['<', name, this.attributes(attrs), '>']; | |
}, | |
closingTag: function(name) { | |
return ['</', name, '>']; | |
}, | |
build: function(name, attrs, children) { | |
attrs = attrs || {}; children = children || []; | |
if (children.length == 0) { | |
this.parts = this.selfClosingTag(name, attrs); | |
} else { | |
this.parts = [this.openingTag(name, attrs), | |
children, this.closingTag(name)]; | |
} | |
return this.parts; | |
}, | |
toString: function() { | |
return flatten(this.parts).join(''); | |
} | |
} | |
$.each(("p|div|span|strong|em|img|table|tr|td|th|thead|tbody|tfoot|pre|code|" + | |
"h1|h2|h3|h4|h5|h6|ul|ol|li|form|input|textarea|legend|fieldset|" + | |
"select|option|blockquote|cite|br|hr|dd|dl|dt|address|a|button|abbr|acronym|" + | |
"script|link|style|bdo|ins|del|object|param|col|colgroup|optgroup|caption|" + | |
"label|dfn|kbd|samp|var").split("|"), function(i, el) { | |
HTMLBuilder.prototype[el] = HTMLBuilder.functionFor(el); | |
}); | |
$.build = function(func) { | |
html = new HTMLBuilder; | |
func(html); | |
return $(html.toString()); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment