Skip to content

Instantly share code, notes, and snippets.

@akx
Forked from neilj/gist:1532562
Created February 21, 2012 18:41
Show Gist options
  • Save akx/1878050 to your computer and use it in GitHub Desktop.
Save akx/1878050 to your computer and use it in GitHub Desktop.
Sugared DOM: Better Than Templates
# Note: This is actually Coco (http://github.com/satyr/coco), not CoffeeScript.
# I haven't tested this, just wanted to see how concise I could make of the Coco implementation.
el = let
doc = document
directProperties = {
class: \className, \className, \defaultValue,
for: \htmlFor, html: \innerHTML, text: \textContent, \value
}
booleanProperties = {+checked, +defaultChecked, +disabled, +multiple, +selected}
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
setProperty = (el, key, value) ->
if prop = directProperties[key] then return el[prop] = (if value === null then "" + value else "")
if booleanProperties[key] then return el[key] = !!value
if value === null then return el.removeAttribute key
return el.setAttribute key, '' + value
appendChildren = !(el, children) ->
for node of children
continue unless node
if isArray node then appendChildren el, node; continue
node = doc.createTextNode node if typeof node === \string
el.appendChild node
splitter = /(#|\.)/
create = !(tag, props, children) ->
if isArray props then children = props; props = null
if splitter.test tag
parts = tag.split splitter
tag = parts.shift!
props ||= {}
for i from 0 til parts.length by 2
if parts[i] === \# then props.id = parts[i + 1]
else props.className = (props.className || "") + " " + parts[i + 1]
el = doc.createElement tag
setProperty el, prop, prop[value] for prop in props if props
appendChildren el, children if children
return el
return create
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment