Skip to content

Instantly share code, notes, and snippets.

@jairoFernandez
Created October 23, 2017 22:41
Show Gist options
  • Save jairoFernandez/f858362b7f341b3911042d5da722e495 to your computer and use it in GitHub Desktop.
Save jairoFernandez/f858362b7f341b3911042d5da722e495 to your computer and use it in GitHub Desktop.
MediatorPattern
var Task = require('./task');
var NotificationService = require('./services/notificationService');
var AuditingService = require('./services/auditingService');
var LoggingService = require('./services/loggingService');
var mediator = require('./mediator');
var notificationService = new NotificationService();
var auditingService = new AuditingService();
var logginService = new LoggingService();
var task1 = new Task({name:"Tarea 1 de prueba"});
mediator.subscribe('complete', notificationService, notificationService.update);
mediator.subscribe('complete', logginService, logginService.update);
mediator.subscribe('complete', auditingService, auditingService.update);
task1.complete = function(){
mediator.publish('complete', this);
Task.prototype.complete.call(this);
}
task1.complete();
var mediator = (function(){
var channels = {};
var subscribe = function(channel, context, func){
if(!mediator.channels[channel]){
mediator.channels[channel] = [];
}
mediator.channels[channel].push({
context: context,
func: func
});
}
var publish = function(channel){
if(!this.channels[channel]){
return false;
}
var args = Array.prototype.slice.call(arguments, 1);
for(var i=0; i < mediator.channels[channel].length; i++){
var sub = mediator.channels[channel][i];
sub.func.apply(sub.context, args);
}
}
return{
channels: {},
subscribe: subscribe,
publish: publish
}
}());
module.exports = mediator;
var auditingService = function(){
var message = "Auditing ";
this.update = function(task){
console.log(message + task.name);
}
}
module.exports = auditingService;
var loggingService = function(){
var message = "Logging ";
this.update = function(task){
console.log(message + task.name);
}
}
module.exports = loggingService;
var notificationService = function(){
var message = "Notifying h... ";
this.update = function(task){
console.log(message + task.name);
}
}
module.exports = notificationService;
var Task = function(data){
this.name = data.name;
this.completed = false;
}
Task.prototype.complete = function(){
console.log('Completed task: ' + this.name);
this.completed = true;
}
Task.prototype.save = function(){
console.log('saving task: ' + this.name);
}
module.exports = Task;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment