Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. 'use strict';
  2.  
  3. function Behavior(value) {
  4. this.s = [];
  5. this.v = value;
  6. }
  7.  
  8. Behavior.prototype = (function() {
  9. var inits = [];
  10. return {
  11. next : function(value) {
  12. if (value != this.v) {
  13. this.v = value;
  14. for(var s in this.s)
  15. this.s[s](value);
  16. }
  17. },
  18. value : function() {
  19. return this.v;
  20. },
  21. subscribe : function(cb, init) {
  22. this.s.push(cb);
  23. if (typeof init === 'function') inits.push(init);
  24. },
  25. init : function() {
  26. for (var i in inits) inits[i]();
  27. inits = [];
  28. },
  29. link : function(b, f) {
  30. var t = this;
  31. function cb(v) {
  32. t.next(f(v));
  33. }
  34. cb(b.value());
  35. b.subscribe(cb);
  36. }
  37. };
  38. })();
  39.  
  40. function make(value) { return new Behavior(value); }
  41.  
  42. var idGen = (function() {
  43. var ctr = 0, re = /^<(\w+)([ >])/;
  44. return function() {
  45. var id = '' + ctr++;
  46. return { v : id, r : function(s) {
  47. return s.replace(re, '<$1 id="' + id + '"$2');
  48. }}
  49. };
  50. })();
  51.  
  52. function Select(b, f) {
  53. var id = idGen();
  54. if (document) b.subscribe(function(v) {
  55. document.getElementById(id.v).outerHTML = id.r(f(v));
  56. b.init();
  57. });
  58. return id.r(f(b.value()));
  59. }
  60.  
  61. function Edit(text, classes) {
  62. var id = idGen(), dom;
  63. if (document) text.subscribe(
  64. function(v) { dom.value = v; },
  65. function() {
  66. console.log('init!');
  67. dom = document.getElementById(id.v);
  68. dom.onchange = function() {
  69. text.next(dom.value);
  70. };
  71. }
  72. );
  73. return '<input type="text" id="' + id.v + '" class="' + classes.join(' ') + '" value="' + text.value() + '">';
  74. }
  75.  
  76. /*var b = make('test');
  77. var a = make('ppp');
  78.  
  79. console.log(b.value());
  80. b.subscribe(function(val) { console.log('b =', val); })
  81. a.subscribe(function(val) { console.log('a =', val); })
  82.  
  83.  
  84. b.link(a, function(v) { return '123' + v});
  85.  
  86. //a.next('567');
  87.  
  88. document.body.insertAdjacentHTML('beforeend', Select(b, (v) => '<H1> b = ' + v + '</H1>'));
  89.  
  90. document.body.insertAdjacentHTML('beforeend', Edit(a, []));
  91.  
  92. b.init();
  93.  
  94. b.next('next');
  95.  
  96. //a.next('text');
  97. //a.next('toxt');
  98. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement