Guest User

Untitled

a guest
Jan 16th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <title>Dom expression binding</title>
  3. <body>
  4. <script>
  5. /**
  6. * placeholder element
  7. */
  8. function $() {
  9. const DOMNode = document.createTextNode('{{}}');
  10. return {
  11. DOMNode,
  12. placeholders: [DOMNode]
  13. };
  14. }
  15.  
  16. function t(text) {
  17. return {
  18. DOMNode: document.createTextNode(text),
  19. placeholders: []
  20. };
  21. }
  22.  
  23. function click(element, handler) {
  24. element.DOMNode.addEventListener('mousedown', handler);
  25. return element;
  26. }
  27.  
  28. function h(tagname, ...children) {
  29. const l = children.length;
  30. const DOMNode = document.createElement(tagname);
  31. let i = 0,
  32. placeholders = [];
  33.  
  34. for (let i = 0; i < l; i++) {
  35. DOMNode.appendChild(children[i].DOMNode);
  36. placeholders = placeholders.concat(children[i].placeholders);
  37. }
  38.  
  39. return { DOMNode, placeholders };
  40. }
  41.  
  42. function wire(template, ...expressions) {
  43. const l = template.placeholders.length;
  44. let placeholders = template.placeholders;
  45. for (let i = 0; i < l; i++) {
  46. placeholders[i].parentNode.replaceChild(expressions[i].DOMNode, placeholders[i]);
  47. }
  48. return {
  49. ...template,
  50. placeholders: expressions.map(e => e.DOMNode)
  51. };
  52. }
  53.  
  54. function createComponent(template, setprops) {
  55. let tmpl = template;
  56. return function(props) {
  57. return tmpl = wire(tmpl, ...(setprops(props)));
  58. };
  59. }
  60.  
  61. function bind(parent, component) {
  62. parent.appendChild(component.DOMNode);
  63. }
  64.  
  65. function test() {
  66. const myComp = createComponent(
  67. h('div',
  68. h('ul',
  69. h('li', $())),
  70. $(),
  71. click(
  72. h('button',
  73. t('click me')),
  74. () => console.log('ahoj'))),
  75. ({text, div}) =>
  76. [t(text), div, ]
  77. );
  78.  
  79. bind(document.body, myComp({ text: 'ahoj', div: h('div', t('ahoj z divu'))}));
  80.  
  81. setTimeout(() => myComp({ text: 'ahodsfsj', div: h('div', t(' jak se mas'))}), 3000);
  82. }
  83.  
  84. test();
  85. </script>
Add Comment
Please, Sign In to add comment