Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

8/07/2013

Mediator design pattern with coffeescript

This is second pattern in series of Javascript design patterns implemented with coffeescript.
It can be found here:

Coffeeversion:

//
#Behavioral
#Mediator - classical object-oriented design patterns with Coffeescript
#Global objects are here just for testing in the browser
this.mediator = 
    mediate:(x)->
        if x is "from obj1"
            obj2.receive(x)
        else
            obj1.receive(x)
        
this.obj1 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj1, I just received this message from " + x + " with the help of mediator"

this.obj2 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj2, I just received this message from " + x + " with the help of mediator"
//

Compiled to vanillajs:

//
// Generated by CoffeeScript 1.6.2
(function() {
  this.mediator = {
    mediate: function(x) {
      if (x === "from obj1") {
        return obj2.receive(x);
      } else {
        return obj1.receive(x);
      }
    }
  };

  this.obj1 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj1, I just received this message from " + x + " with the help of mediator");
    }
  };

  this.obj2 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj2, I just received this message from " + x + " with the help of mediator");
    }
  };

}).call(this);

//

Thanks for visiting my blog.

No comments:

Post a Comment