Mediator pattern in javascript
by bhupendra negi
JavaScript
// crreate Task constructor
function Task(data) {
this.name = data.name;
this.user = data.user;
this.project = data.project;
this.priority = data.priority;
this.completed = data.completed || false;
}
Task.prototype.completed = function() {
console.log("Completing Task with name :" + this.name);
this.completed = true;
}
Task.prototype.save = function() {
console.log("Saving Task : " + this.name);
}
// creating observers
var loggingService = function() {
var message = 'Logging!';
this.update = function(task) {
console.log(message + ' for' + task.user + ' ,task:' + task.name);
}
}
var notificationService = function() {
var message = "notify";
this.update = function(task) {
console.log(message + ' for' + task.user + ' ,task:' + task.name);
}
}
var not = new notificationService();
var ls = new loggingService();
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 (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
}
}());
// subscribe to channels :
mediator.subscribe('complete',not,not.update);
mediator.subscribe('complete',ls,ls.update);
var task1 = new Task({
name: 'demo for mediator',
user: 'john'
})
task1.complete = function() {
mediator.publish('complete',this);
Task.prototype.completed.call(this);
}
task1.complete();