Dustin Diaz's Publisher class to achieve a publisher-subscriber pattern in javascript


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



Copy this code and paste it in your HTML
  1. /*
  2. * Publisher Host (c) Creative Commons 2006
  3. * http://creativecommons.org/licenses/by-sa/2.5/
  4. * Author: Dustin Diaz | http://www.dustindiaz.com
  5. * Reference: http://www.dustindiaz.com/basement/publisher.html
  6. */
  7. /*
  8. * @Class: Publisher
  9. * Requires:
  10. * Array.prototype.forEach
  11. * Array.prototype.some
  12. * See Sugar Arrays at:
  13. * http://www.dustindiaz.com/basement/sugar-arrays.html
  14. * Constructor: The almighty holder of its subscribers
  15. */
  16.  
  17. /* Minified */
  18. function Publisher(){this.subscribers=[];}Publisher.prototype.deliver=function(data,thisObj){var scope=thisObj||window;this.subscribers.forEach(function(el){el.call(scope,data);});};Function.prototype.subscribe=function(publisher){var that=this;var alreadyExists=publisher.subscribers.some(function(el){if(el===that){return;}});if(!alreadyExists){publisher.subscribers.push(this);}return this;};Function.prototype.unsubscribe=function(publisher){var that=this;publisher.subscribers=publisher.subscribers.filter(function(el){if(el!==that){return el;}});return this;};
  19.  
  20. /* Full */
  21. function Publisher() {
  22. this.subscribers = [];
  23. }
  24. /*
  25. * @desc: deliver | the delivery method
  26. * @param: data | The data you want to send to your subscribers
  27. * @param: thisObj | The scope you want to execute your callbacks
  28. */
  29. Publisher.prototype.deliver = function(data, thisObj) {
  30. var scope = thisObj || window;
  31. this.subscribers.forEach(
  32. function(el) {
  33. el.call(scope, data);
  34. }
  35. );
  36. };
  37. /*
  38. * @desc: subscribe | Gives all function objects
  39. * the ability to subscribe to a Publisher Object
  40. * @param: publisher | The Publisher Object you wish to subscribe to
  41. */
  42. Function.prototype.subscribe = function(publisher) {
  43. var that = this;
  44. var alreadyExists = publisher.subscribers.some(
  45. function(el) {
  46. if ( el === that ) {
  47. return;
  48. }
  49. }
  50. );
  51. if ( !alreadyExists ) {
  52. publisher.subscribers.push(this);
  53. }
  54. return this;
  55. };
  56. /*
  57. * @desc: unsubscribe | Gives all function objects
  58. * the ability to "unsubscribe" to a Publisher Object
  59. * @param: publisher | The Publisher Object you wish to unsubscribe to
  60. */
  61. Function.prototype.unsubscribe = function(publisher) {
  62. var that = this;
  63. publisher.subscribers = publisher.subscribers.filter(
  64. function(el) {
  65. if ( el !== that ) {
  66. return el;
  67. }
  68. }
  69. );
  70. return this;
  71. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.