johnny-dreamguns
10/7/2019 - 9:36 AM

Mediator

// MEDIATOR

const Task = require('./task');

function notificationService () {
  const message = 'Notifying ';
  this.update = function(task) {
    console.log(message + task.user + ' for task ' + task.name);
  }
};

function loggingService () {
  const message = 'Logging ';
  this.update = function(task) {
    console.log(message + task.user + ' for task ' + task.name);
  }
};

const mediator = (() => {
  const channels = {};

  const subscribe = function(channel, context, func) {
    if(!mediator.channels[channel]){
      mediator.channels[channel] = [];
    }
    mediator.channels[channel].push({
      context,
      func
    });
  }

  const publish = function(channel) {
    if(!mediator.channels[channel]) {
      return false;
    }

    console.log(arguments);
    const args = Array.prototype.slice.call(arguments, 1);

    for(let i=0; i<mediator.channels[channel].length; i++){
      let sub = mediator.channels[channel][i];
      sub.func.apply(sub.context, args);
    }
  }

  return {
    channels,
    subscribe,
    publish
  }
})();


const not = new notificationService();
const log = new loggingService();

mediator.subscribe('complete', not, not.update);
mediator.subscribe('complete', log, log.update);

const t1 = new Task({
  name: 'Test',
  user: 'John'
});

t1.complete = function() {
  mediator.publish('complete', this);
  Task.prototype.complete.call(this);
}

t1.complete();