Last active
March 20, 2017 16:42
-
-
Save TCotton/d85e879fdbf856ddae3511652f9260f0 to your computer and use it in GitHub Desktop.
Mediator pattern es3 to es6
This file contains 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
// es3: https://gist.github.com/addyosmani/1837327 | |
var mediator = (function() { | |
// Subscribe to an event, supply a callback to be executed | |
// when that event is broadcast | |
var subscribe = function(channel, fn) { | |
if (!mediator.channels[channel]) mediator.channels[channel] = []; | |
mediator.channels[channel].push({ | |
context: this, | |
callback: fn | |
}); | |
return this; | |
}, | |
// Publish/broadcast an event to the rest of the application | |
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 this; | |
}; | |
return { | |
channels: {}, | |
publish: publish, | |
subscribe: subscribe, | |
installTo: function(obj) { | |
obj.subscribe = subscribe; | |
obj.publish = publish; | |
} | |
}; | |
}()); | |
//es6 | |
const mediator = ((() => { | |
/** | |
* @description Subscribe to an event, supply a callback to be executed when that event is broadcast | |
* @param store {string} | |
* @param fn {function} | |
* @returns {subscribe} {object} | |
*/ | |
const subscribe = function(store, fn) { | |
if (!mediator.stores[store]) { | |
mediator.stores[store] = []; | |
} | |
mediator.stores[store].push({ | |
context: this, | |
callback: fn | |
}); | |
return this; | |
}; | |
/** | |
* @description Publish/broadcast an event to the rest of the application | |
* @param store {string} | |
* @param args {object} | |
* @returns {*||boolean} | |
*/ | |
const publish = function(store, ...args) { | |
if (!mediator.stores[store]) { | |
return false; | |
} | |
for (let value of mediator.stores[store]) { | |
const subscription = value; | |
subscription.callback.apply(subscription.context, args); | |
} | |
return this; | |
}; | |
return { | |
stores: {}, | |
publish, | |
subscribe, | |
installTo(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