require(['mediator/init'],function(init) {
var examples = {
mediator: init
}
for (var example in examples) {
examples[example].init();
}
});
define(function(require) {
'use strict';
return {
init: function() {
var mediator, colleague1, colleague2, colleague3;
var Mediator = require('mediator/mediator');
var colleague = require('mediator/colleague');
mediator = new Mediator();
colleague1 = colleague.create('colleague1', mediator);
colleague2 = colleague.create('colleague2', mediator);
colleague3 = colleague.create('colleague3', mediator);
colleague1.sendMessage('Hey there', 'colleague2');
colleague2.sendMessage('Hi colleague1', 'colleague1');
colleague3.sendMessage('Hey guys!');
}
};
});
define(function() {
'use strict';
var Colleague = function(id, mediator) {
this.id = id;
this.mediator = mediator;
};
Colleague.prototype.receiveMessage = function(message) {
console.log('Module', this.id, 'received message:', message);
return true;
};
Colleague.prototype.sendMessage = function(message, recipientId) {
(recipientId) ? this.mediator.send(recipientId, message): this.mediator.broadcast(message, this);
};
return {
create: function(id, mediator) {
var that = new Colleague(id, mediator);
mediator.register(that);
return that;
}
};
});
define(function() {
'use strict';
var Mediator = function() {
this.colleagues = [];
};
Mediator.prototype.register = function(colleague) {
this.colleagues.push(colleague);
};
Mediator.prototype.send = function(recipientId, message) {
this.colleagues.some(function(colleague) {
if (colleague.id === recipientId) {
return colleague.receiveMessage(message);
}
});
};
Mediator.prototype.broadcast = function(message, sender) {
this.colleagues.forEach(function(colleague) {
if (colleague.id !== sender.id) {
colleague.receiveMessage(message);
}
});
};
return Mediator;
});