|
| 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