Re: Simplifying element creation

* Ryosuke Niwa wrote:
>It simplified
>    var table = document.createElement('table');
>    table.appendChild(document.createElement('tbody'));
>...
>    for (var i = 0; i < labels.length; i++) {
>        var tableRow = document.createElement('tr');
>        var titleCell = document.createElement('td');
>        titleCell.appendChild(document.createTextNode(labels[i]));
>        tableRow.appendChild(titleCell);
>
>        var valueCell = document.createElement('td');
>        var bar = document.createElement('span');
>        bar.className = 'bar';
>        bar.style.width = <some expression> + '%';
>        valueCell.appendChild(bar);
>
>        var valueContainer = document.createElement('span');
>        valueContainer.appendChild(document.createTextNode(values[i]));
>        valueContainer.className = 'value-container';
>        valueCell.appendChild(valueContainer);
>        tableRow.appendChild(valueCell);
>        table.childNodes[0].appendChild(tableRow);
>    }
>    element.appendChild(table);
>to
>    var table = Element.create('table', {}, [Element.create('tbody')]);
>...
>    for (var i = 0; i < labels.length; i++) {
>        table.childNodes[0].append(
>            Element.create('tr', {}, [
>                Element.create('td', {}, [labels[i]]),
>                Element.create('td', {}, [
>                    Element.create('span', {'class': 'bar', 'style':
>'width: ' + <same expression> + '%'}),
>                    Element.create('span', {'class': 'value-container'},
>[values[i]])])
>                ])
>        );
>    }
>    element.appendChild(table);

Maybe you are looking for templates, say something like

  <template name='example' white-space='tidy'>
  <tr>
    <td>{0}</td>
    <td>
      <span class='bar' style='width: {1}%'>
        <span class='value-container'>{2}</span>
      </span>
    </td>
  </tr>
  </template>
  ...
  var node = fill("example", labels[i], <some expression>, values[i]);

or with named parameters (make some names up), say,

  var node = fill("example", {
    '0': labels[i],
    '1': <some expression>,
    '2': values[i]
  });

That would seem to suit your use case better.
-- 
Björn Höhrmann · mailto:bjoern@hoehrmann.de · http://bjoern.hoehrmann.de
Am Badedeich 7 · Telefon: +49(0)160/4415681 · http://www.bjoernsworld.de
25899 Dagebüll · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/ 

Received on Monday, 14 November 2011 23:41:47 UTC