Posted By

nerdfiles on 02/08/10


Tagged

javascript oop


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ts


Observer pattern (again)


 / Published in: JavaScript
 

URL: http://www.dustindiaz.com/basement/javascript-observer-class.html

  1. <!DOCTYPE HTML>
  2. <html lang="en">
  3. <head>
  4. <title></title>
  5. <script>
  6.  
  7. function Observer() {
  8. this.fns = [];
  9. }
  10.  
  11. Observer.prototype = {
  12. subscribe: function(fn) {
  13. this.fns.push(fn);
  14. },
  15.  
  16. unsubscribe: function(fn) {
  17. this.fns = this.fns.filter(
  18. function(el) {
  19. if ( el !== fn ) {
  20. return el;
  21. }
  22. }
  23. );
  24. },
  25.  
  26. fire: function(o, thisObj) {
  27. var scope = thisObj || window;
  28. this.fns.forEach(
  29. function(el) {
  30. el.call(scope, o);
  31. }
  32. );
  33. }
  34. };
  35.  
  36. var o = new Observer;
  37. o.fire('here is my data');
  38.  
  39. var fn = function fn() {
  40. console.log('data data');
  41. };
  42. var fn3 = function fn3() {
  43. console.log('data data3 ');
  44. };
  45. o.subscribe(fn);
  46. o.subscribe(fn3);
  47. o.unsubscribe(fn);
  48. o.fire('here is my data');
  49.  
  50. </script>
  51. </head>
  52. <body></body>
  53. </html>

Report this snippet  

You need to login to post a comment.