Re: [whatwg/dom] Proposal to improve the DOM creation api (#150)

I saw your implementation, here's a short one that does Domenic's example:
```
function h(s, ...o){ // strings parts (length n) and object variables (length n-1)
 let html = ''; //let's stupidly concatenate for the moment
 for (let i=0; i<o.length; i++){
  if (typeof o[i]==='function'){// an event listener
   html += s[i];
  } else if (Array.isArray(o[i]) || o[i] instanceof Element) { // children
   html += s[i]+`<!--c${i}-->`;
  } else {
   html += s[i]+o[i];
  }
 }
 const el = new Range().createContextualFragment(html+s[s.length-1]).firstElementChild;
 // recover all listeners placeholder and childrens, they should be in same order (tree-order)
 const nodes = [el].concat(...el.querySelectorAll('*'));
 const comments = [].concat(...nodes.map(i=>Array.prototype.filter.call(i.childNodes, c=>c.nodeType==8)));
 const listeners = [].concat(...nodes.map(i=>Array.prototype.filter.call(i.attributes, a=>a.name.startsWith('on'))));
 for (let i=0; i<o.length; i++){
  if (typeof o[i]==='function'){ // listeners
   const a = listeners.shift();
   a.ownerElement.addEventListener(a.name.slice(2), o[i]);
   a.ownerElement.removeAttribute(a.name);
  } else if(Array.isArray(o[i]) || o[i] instanceof Element) { // children
   const c = comments.shift();
   c.parentNode.replaceChild(Array.isArray(o[i])?frag(o[i]):o[i], c);
  }
 }
 return el;
}
function frag(a){
 const f=new DocumentFragment();
 a.forEach(el => f.appendChild(el));
 return f;
}
h`<ul class="something">${[{text:'lk'}].map(({text}) => h`
  <li onclick=${e=>console.log('li',text)}>
    ${text}
    <span onclick=${e=>console.log('x')}>✕</span>
  </li>`)}
</ul>`
```

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/150#issuecomment-239332156

Received on Friday, 12 August 2016 00:25:18 UTC