Skip to content

Commit b7f69b6

Browse files
committed
added mediator pattern
1 parent 572956c commit b7f69b6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

pattern/mediator-pattern.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
var window = window || null;
2+
var Mediator = ( function( window, undefined ) {
3+
4+
function Mediator() {
5+
this._topics = {};
6+
}
7+
8+
Mediator.prototype.subscribe = function mediatorSubscribe( topic, callback ) {
9+
if( ! this._topics.hasOwnProperty( topic ) ) {
10+
this._topics[ topic ] = [];
11+
}
12+
13+
this._topics[ topic ].push( callback );
14+
return true;
15+
};
16+
17+
Mediator.prototype.unsubscribe = function mediatorUnsubscrive( topic, callback ) {
18+
if( ! this._topics.hasOwnProperty( topic ) ) {
19+
return false;
20+
}
21+
22+
for( var i = 0, len = this._topics[ topic ].length; i < len; i++ ) {
23+
if( this._topics[ topic ][ i ] === callback ) {
24+
this._topics[ topic ].splice( i, 1 );
25+
return true;
26+
}
27+
}
28+
29+
return false;
30+
};
31+
32+
Mediator.prototype.publish = function mediatorPublish() {
33+
var args = Array.prototype.slice.call( arguments );
34+
var topic = args.shift();
35+
36+
if( ! this._topics.hasOwnProperty( topic ) ) {
37+
return false;
38+
}
39+
40+
for( var i = 0, len = this._topics[ topic ].length; i < len; i++ ) {
41+
this._topics[ topic ][ i ].apply( undefined, args );
42+
}
43+
return true;
44+
};
45+
46+
return Mediator;
47+
48+
} )( window );
49+
50+
// example subscriber function
51+
var Subscriber = function ExampleSubscriber( myVariable ) {
52+
console.log( myVariable );
53+
};
54+
55+
// example usages
56+
var myMediator = new Mediator();
57+
myMediator.subscribe( 'some event', Subscriber );
58+
myMediator.publish( 'some event', 'foo bar' ); // console logs "foo bar"

0 commit comments

Comments
 (0)