Created
September 7, 2015 13:15
-
-
Save piotrlewandowski/5275ede2c432c4a7526d to your computer and use it in GitHub Desktop.
JS Mediator Pattern Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mediator = (function() { | |
'use strict'; | |
var | |
subscribe = function(channel, fn) { | |
if (!mediator.channels[channel]) { | |
mediator.channels[channel] = []; | |
} | |
mediator.channels[channel].push({ context: this, callback: fn }); | |
return this; | |
}, | |
publish = function(channel) { | |
if (!mediator.channels[channel]) { | |
return false; | |
} | |
var args = Array.prototype.slice.call(arguments, 1); | |
for (var i = 0, l = mediator.channels[channel].length; i < l; i++) { | |
var subscription = mediator.channels[channel][i]; | |
subscription.callback.apply(subscription.context, args); | |
} | |
}; | |
return { | |
channels: {}, | |
publish: publish, | |
subscribe: subscribe, | |
installTo: function(obj) { | |
obj.subscribe = subscribe; | |
obj.publish = publish; | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment