Skip to content

Instantly share code, notes, and snippets.

@jenya239
Last active June 29, 2017 00:54
Show Gist options
  • Save jenya239/5a163297c0c4ced0b955ba8e93a23561 to your computer and use it in GitHub Desktop.
Save jenya239/5a163297c0c4ced0b955ba8e93a23561 to your computer and use it in GitHub Desktop.
create_node.coffee
#ToDo on handlers, many id & classes, more smart names?
#oop?, https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes, shortcuts?
#!? html -> vdom
#? $class: , $node$class: , $$id ?
#? postcss ?
#? class names like BEM?
window.t = '#ss':
data: ff: 2, ee: 4
img: cls: 'asdf', src: 'https://elixir-lang.org/images/logo/logo.png', width: 100
css: margin: '0px', padding: '1px'
'c': [ span: html: 'asdfffa', b: 'vvvvv' ]
typeIsArray = ( value ) ->
value and
typeof value is 'object' and
value instanceof Array and
typeof value.length is 'number' and
typeof value.splice is 'function' and
not ( value.propertyIsEnumerable 'length' )
window.create_nodes = ( s ) ->
name = Object.keys( s )[0]
val = s[ name ]
attrs = {}
children = []
if name[0] == '#'
node = 'div'
attrs.id = name.substring 1
else if name[0] == '.'
node = 'div'
attrs.class = name.substring 1
else
node = name
attrs.class = val.class || val.cls
if typeof val is 'string'
attrs.html = val
else
for k, v of val
if k in 'id,cls,class,data,css,text,html,on,src,width,height,href,type,value,name,rel'.split( ',' )
attrs[ k ] = v
else if typeIsArray v
for child in v
children.push create_nodes child
else
el = {}
el[ k ] = v
children.push create_nodes( el )
res = $( "<#{ node }>", attrs )
for child in children
res.append child
id = child.attr 'id'
cls = child.attr 'class'
nn = child[0].nodeName.toLowerCase()
res[ '$' + id ] = child if id
res[ '$' + cls ] = child if cls and !res[ '$' + cls ]
res[ '$' + nn ] = child if !res[ '$' + nn ] and !id and !cls
res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment