fork download
  1. /**
  2.   * Element rendering engine.
  3.   */
  4. var tmpl = {
  5. /**
  6.   * Renders element by specification.
  7.   *
  8.   * @param spec
  9.   * elements specification
  10.   * @return DOM element
  11.   */
  12. render : function(spec) {
  13. var elem = document.createElement(spec[0]);
  14. if (spec.length == 1) {
  15. return elem;
  16. }
  17. var maybeAttrs = spec[1];
  18. var n = 2;
  19. if (this._isHash(maybeAttrs)) {
  20. this._applyAttrs(elem, maybeAttrs);
  21. } else {
  22. n = 1;
  23. }
  24. while (n < spec.length) {
  25. this._makeElem(elem, spec[n++]);
  26. }
  27. return elem;
  28. },
  29.  
  30. /**
  31.   * Sets element attributes.
  32.   *
  33.   * @param e
  34.   * element to set attributes
  35.   * @param attrs
  36.   * attributes object
  37.   */
  38. _applyAttrs : function(e, attrs) {
  39. for (attr in attrs) {
  40. if (attrs.hasOwnProperty(attr)) {
  41. e.setAttribute(attr, attrs[attr]);
  42. }
  43. }
  44. },
  45.  
  46. /**
  47.   * Creates nested node.
  48.   *
  49.   * @param elem
  50.   * element insert node to
  51.   * @param x
  52.   * value to create node from
  53.   * @return DOM node
  54.   */
  55. _makeElem : function(elem, x) {
  56. var type = typeof (x);
  57. var i = 0;
  58. if (type == "string") {
  59. elem.appendChild(document.createTextNode(x));
  60. } else if (x instanceof Array) {
  61. // flatten array of nested elements
  62. if (x[0] instanceof Array) {
  63. while (i < x.length) {
  64. this._makeElem(elem, x[i++]);
  65. }
  66. } else {
  67. elem.appendChild(this.render(x));
  68. }
  69. } else if (x instanceof Function) {
  70. this._makeElem(elem, x.apply(null));
  71. }
  72. },
  73.  
  74. /**
  75.   * Checks whether it's argument a hash or not.
  76.   *
  77.   * @param x
  78.   * value to test
  79.   * @return true if object is a hash, false otherwise
  80.   */
  81. _isHash : function(x) {
  82. return typeof (x) == "object" && !(x instanceof Array);
  83. }
  84. };
Success #stdin #stdout 0.3s 213696KB
stdin
Standard input is empty
stdout
Standard output is empty