Posted By

timsommer on 07/31/12


Tagged

javascript html Mediator designpattern


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

scottshane


JavaScript Mediator Pattern


 / Published in: JavaScript
 

In software engineering, a mediator is a behavioral design pattern that allows us to expose a unified interface through which the different parts of a system may communicate. If it appears a system may have too many direct relationships between modules (colleagues), it may be time to have a central point of control that modules communicate through instead. The Mediator promotes loose coupling by ensuring that instead of modules referring to each other explicitly, their interaction is handled through this central point.

If you would prefer a real-world analogy, consider a typical airport traffic control system. A tower (mediator) handles what planes can take off and land because all communications (notifications being listened out for or broadcast) are done from the planes to the control tower, rather than from plane-to-plane. A centralized controller is key to the success of this system and that's really the role a mediator plays in software design.

  1. var mediator = (function(){
  2.  
  3. // Storage for our topics/events
  4. var channels = {};
  5.  
  6. // Subscribe to an event, supply a callback to be executed
  7. // when that event is broadcast
  8. var subscribe = function(channel, fn){
  9. if (!channels[channel]) channels[channel] = [];
  10. channels[channel].push({ context: this, callback: fn });
  11. return this;
  12. };
  13.  
  14. // Publish/broadcast an event to the rest of the application
  15. var publish = function(channel){
  16. if (!channels[channel]) return false;
  17. var args = Array.prototype.slice.call(arguments, 1);
  18. for (var i = 0, l = channels[channel].length; i < l; i++) {
  19. var subscription = channels[channel][i];
  20. subscription.callback.apply(subscription.context, args);
  21. }
  22. return this;
  23. };
  24.  
  25. return {
  26. publish: publish,
  27. subscribe: subscribe,
  28. installTo: function(obj){
  29. obj.subscribe = subscribe;
  30. obj.publish = publish;
  31. }
  32. };
  33. }());
  34.  
  35. /*** Usage ***/
  36. (function( m ){
  37. // Set a default value for 'person'
  38. var person = "Luke";
  39. // Subscribe to a topic/event called 'nameChange' with
  40. // a callback function which will log the original
  41. // person's name and (if everything works) the incoming
  42. // name
  43. m.subscribe('nameChange', function( arg ){
  44. console.log( person ); // Luke
  45. person = arg;
  46. console.log( person ); // David
  47. });
  48.  
  49. // Publish the 'nameChange' topic/event with the new data
  50. m.publish( 'nameChange', 'David' );
  51.  
  52. })( mediator );

Report this snippet  

You need to login to post a comment.