Class to implement publisher


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /*
  2. @author gwilliams
  3. From the article http://justanotherdeveloper.co.uk/2008/07/24/publisher-subscriber-pattern/
  4. */
  5.  
  6. var Publisher = function(){
  7.  
  8. var _subscribers = [];
  9.  
  10. return {
  11.  
  12. /*
  13. * Pushes the subscribers callback function into
  14. * the private _subscribers property.
  15. */
  16. subscribe: function(fn){
  17. _subscribers.push(fn);
  18. },
  19.  
  20. /*
  21. * Method is used to unsubscribe a subscribers callback function
  22. * from the publisher.
  23. */
  24. unsubscribe: function(fn){
  25.  
  26. _newSubscribers = []; // Create an empty subscriber array
  27.  
  28. /*
  29. * Loop through the _subscribers array, checking to see
  30. * whether the function in 'fn' matches any function in
  31. * the _subscribers array, if it doesn't match, push it
  32. * in the _newSubscribers array.
  33. */
  34. for (var i = 0; i < _subscribers.length; i++) {
  35. if (_subscribers[i] !== fn) {
  36. _newSubscribers.push(fn);
  37. }
  38. }
  39.  
  40. /*
  41. * Now the _newSubscribers array only contains the callback
  42. * methods we want we can re-assign it to the private
  43. * _subscribers property.
  44. */
  45. _subscribers = _newSubscribers;
  46. },
  47.  
  48. /*
  49. * Wipes the subscriber list
  50. */
  51. wipe: function(){
  52.  
  53. _subscribers = [];
  54.  
  55. },
  56.  
  57. /*
  58. * Returns all of the current subscribers in an array
  59. */
  60. getSubscribers: function(){
  61. return _subscribers;
  62. }
  63.  
  64. /*
  65. * The notify method is used to invoke all of the callback methods
  66. * in the _subscribers array, o is the property to be sent to the
  67. * subscriber method, this can be anything from a string to an object
  68. * or even JSON.
  69. */
  70. notify: function(o){
  71. for (var i = 0; i < _subscribers.length; i++) {
  72. _subscribers[i].call(o);
  73. }
  74. }
  75.  
  76. }
  77.  
  78. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.