Posted By

nerdfiles on 02/08/10


Tagged

js oop


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

kesla
iroybot


Module, Singleton and Observer Patterns


 / Published in: JavaScript
 

  1. // Module Pattern
  2. var Module = function() {
  3. _private1 = "private";
  4. _history = [];
  5.  
  6. function _privateReturner() {
  7. return _private1;
  8. }
  9.  
  10. function _privateSender(set) {
  11. _history.push("From "+_private1+" to "+set);
  12. _private1 = set;
  13. }
  14.  
  15. function _getHistory() {
  16. return _history;
  17. }
  18.  
  19. return {
  20. publicReturner: _privateReturner,
  21. publicSender: _privateSender,
  22. publicHistory: _getHistory
  23. }
  24. };
  25. /*
  26. var mod = new Module();
  27. console.log(mod._private1); // undefined
  28. console.log(mod.publicReturner()); // private
  29. mod.publicSender("fishly");
  30. mod.publicSender("fishly2");
  31. mod.publicSender("bob");
  32. mod.publicSender("kevin");
  33. console.log(mod.publicReturner()); // fishly
  34. console.log(mod.publicHistory());
  35. */
  36.  
  37. // Singleton Pattern
  38. var Singleton = (function() {
  39. var _private1 = 1;
  40. var _private2 = 2;
  41. var _total = 0;
  42.  
  43. function _privateFunc() {
  44. _total = _private1 + _private2;
  45. }
  46.  
  47. function getter() {
  48. return _total;
  49. }
  50.  
  51. function setterReset(newVar) {
  52. _total = newVar;
  53. }
  54.  
  55. return {
  56. getter: getter,
  57. setterReset: setterReset,
  58. publicVar: 1,
  59. changePrivate: function() {
  60. _privateFunc();
  61. }
  62. }
  63. })();
  64. /*
  65. Singleton.setterReset(0);
  66. console.log(Singleton.getter());
  67. Singleton.changePrivate();
  68. console.log(Singleton.getter());
  69. */
  70.  
  71. // Observer pattern
  72. function Observer() {
  73. this.fns = [];
  74. }
  75.  
  76. Observer.prototype = {
  77. subscribe: function(fn) {
  78. this.fns.push(fn);
  79. },
  80.  
  81. unsubscribe: function(fn) {
  82. this.fns = this.fns.filter(
  83. function(el) {
  84. if ( el !== fn ) {
  85. return el;
  86. }
  87. }
  88. );
  89. },
  90.  
  91. fire: function(o, thisObj) {
  92. var scope = thisObj || window;
  93. this.fns.forEach(
  94. function(el) {
  95. el.call(scope, o);
  96. }
  97. );
  98. }
  99. };
  100. /*
  101. var o = new Observer;
  102. o.fire('here is my data');
  103.  
  104. var fn = function fn() {
  105.   console.log('data data');
  106. };
  107. var fn3 = function fn3() {
  108.   console.log('data data3 ');
  109. };
  110. o.subscribe(fn);
  111. o.subscribe(fn3);
  112. o.unsubscribe(fn);
  113. o.fire('here is my data');
  114. */

Report this snippet  

You need to login to post a comment.