Mediator Pattern
Behavioral design pattern that allows for a unified interface through which the different parts of the system may communicate.
HTML
<h1 id="text">Mediator Design Pattern</h1>
<div id="msgs"></div>
<button id="btn">Click</button>
JavaScript
var mediator = (function () {
var topics = {};
var subscribe = function (topic, fn) {
if (!topics[topic]) {
topics[topic] = [];
}
topics[topic].push({
context: this,
callback: fn
});
return this;
};
var publish = function (topic) {
var args;
if (!topics[topic]) {
return false;
}
args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = topics[topic].length; i < l; i++) {
var subscription = topics[topic][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
publish: publish,
subscribe: subscribe,
installTo: function (obj) {
obj.subscribe = subscribe;
obj.publish = publish;
}
};
})();
// Begin Using Mediator Pattern
var objA = {};
var objB = {};
var btn = document.getElementById('btn');
var txt = document.getElementById('text');
var msgs = document.getElementById('msgs');
mediator.installTo(objA);
mediator.installTo(objB);
mediator.installTo(btn);
objA.subscribe('topic1', function () {
msgs.innerHTML = 'objA fires on publish of "topic1"' + '<br />';
txt.style.color = '#ff0';
});
objB.subscribe('topic2', function () {
msgs.innerHTML += 'objB fires on publish of "topic2"' + '<br />';
var newEl = document.createElement('p');
var newElContent = document.createTextNode("NEW PARAGRAPH ELEMENT brought to you by objB");
newEl.appendChild(newElContent);
//msgs.appendChild(newEl);
for (var i = 0; i < 5; i++) {
var x = newEl.cloneNode(true);
var b = document.createTextNode(i);
x.appendChild(b);
msgs.appendChild(x);
}
document.body.style.backgroundColor = '#f00';
document.body.style.textAlign = 'center';
txt.style.fontSize = '50px';
});
var count = 0;
btn.onclick = function () {
...