Posted By

timsommer on 07/31/12


Tagged

javascript html observer designpattern


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

VeXHarbinger


JavaScript Observer Pattern


 / Published in: JavaScript
 

The Observer pattern is more popularly known these days as the Publish/Subscribe pattern. It is a design pattern which allows an object (known as a subscriber) to watch another object (the publisher), where we provide a means for the subscriber and pub-lisher form a listen and broadcast relationship.

Popular JavaScript libraries such as dojo, jQuery (custom events) and YUI already have utilities that can assist in easily implementing a Pub/Sub system with very little effort.

  1. var pubsub = {};
  2. (function(q) {
  3. var topics = {},
  4. subUid = -1;
  5. // Publish or broadcast events of interest
  6. // with a specific topic name and arguments
  7. // such as the data to pass along
  8. q.publish = function( topic, args ) {
  9. if ( !topics[topic] ) {
  10. return false;
  11. }
  12. var subscribers = topics[topic],
  13. len = subscribers ? subscribers.length : 0;
  14. while (len--) {
  15. subscribers[len].func(topic, args);
  16. }
  17.  
  18. return this;
  19. };
  20. // Subscribe to events of interest
  21. // with a specific topic name and a
  22. // callback function, to be executed
  23. // when the topic/event is observed
  24. q.subscribe = function( topic, func ) {
  25. if (!topics[topic]) {
  26. topics[topic] = [];
  27. }
  28. var token = (++subUid).toString();
  29. topics[topic].push({
  30. token: token,
  31. func: func
  32. });
  33. return token;
  34. };
  35. // Unsubscribe from a specific
  36. // topic, based on a tokenized reference
  37. // to the subscription
  38. q.unsubscribe = function( token ) {
  39. for ( var m in topics ) {
  40. if ( topics[m] ) {
  41. for (var i = 0, j = topics[m].length; i < j; i++) {
  42. if (topics[m][i].token === token) {
  43. topics[m].splice(i, 1);
  44. return token;
  45. }
  46. }
  47. }
  48. }
  49. return this;
  50. };
  51. }( pubsub ));
  52.  
  53.  
  54. //Usage :
  55.  
  56. var testHandler = function (topics, data) {
  57. console.log(topics + ": " + data);
  58. };
  59. // Subscribers basically "subscribe" (or listen)
  60. // And once they've been "notified" their callback functions are invoke
  61. var testSubscription = pubsub.subscribe('example1', testHandler);
  62. // Publishers are in charge of "publishing" notifications about events
  63. pubsub.publish('example1', 'hello world!');
  64. pubsub.publish('example1', ['test', 'a', 'b', 'c']);
  65. pubsub.publish('example1', [{
  66. 'color': 'blue'
  67. }, {
  68. 'text': 'hello'
  69. }]);
  70. // Unsubscribe if you no longer wish to be notified
  71. pubsub.unsubscribe(testSubscription);
  72. // This will fail
  73. pubsub.publish('example1', 'hello again! (this will fail)');

Report this snippet  

You need to login to post a comment.