Posted By

eryoav on 11/12/11


Tagged

DesignPatterns


Versions (?)

pubsub


 / Published in: JavaScript
 

URL: http://jsfiddle.net/LxPrq/

  1. <!DOCTYPE HTML>
  2. <html lang="en-US">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <script>
  9. var pubsub = {};
  10. (function(q) {
  11.  
  12. var topics = {},
  13. subUid = -1;
  14.  
  15. q.publish = function(topic, args) {
  16.  
  17. if (!topics[topic]){
  18. return false;
  19. }
  20.  
  21. setTimeout(function() {
  22. var subscribers = topics[topic],
  23. len = subscribers ? subscribers.length : 0;
  24.  
  25. while(len--) {
  26. subscribers[len].func(topic, args);
  27. }
  28. }, 0);
  29.  
  30. return true;
  31. }
  32.  
  33. q.subscribe = function(topic, func) {
  34.  
  35. if(!topics[topic]) {
  36. topics[topic] = [];
  37. }
  38.  
  39. var token = (++subUid).toString();
  40. topics[topic].push({
  41. //token: token,
  42. func: func
  43. });
  44. return token;
  45. }
  46.  
  47. q.unsubscribe = function(token) {
  48. for (var m in topics) {
  49. if (topics[m]) {
  50. for (var i = 0, j = topics[m].length; i < j; i++) {
  51. if (topics[m][i].token === token) {
  52. topics[m].splice(i, 1);
  53. return token;
  54. }
  55. }
  56. }
  57. }
  58. return false;
  59. };
  60.  
  61. })(pubsub);
  62.  
  63. var testSubscriber = function( topics , data ){
  64. console.log( topics + ": " + data );
  65. };
  66.  
  67. var testSubscription = pubsub.subscribe( 'example1', testSubscriber );
  68.  
  69. pubsub.publish( 'example1', 'hello world!' );
  70. pubsub.unsubscribe( testSubscription );
  71. </script>
  72. </body>
  73. </html>

Report this snippet  

You need to login to post a comment.