Skip to content

Instantly share code, notes, and snippets.

@evaldosantos
Created March 15, 2017 13:25
Show Gist options
  • Save evaldosantos/7982de8e1f30fc53e386743c6347d27f to your computer and use it in GitHub Desktop.
Save evaldosantos/7982de8e1f30fc53e386743c6347d27f to your computer and use it in GitHub Desktop.
var EventBus = {
events: {},
subscribe: function(event, listener) {
// create the event if not yet created
if(!this.events[event]) this.events[event] = [];
// add the listener
this.events[event].push(listener);
},
publish: function(event, data) {
// return if the event doesn't exist, or there are no listeners
if(!this.events[event] || this.events[event].length < 1) return;
// send the event to all listeners
this.events[event].forEach(function(listener) {
listener(data || {});
});
}
};
EventBus.subscribe('foo', alert);
EventBus.publish('foo', 'Hello World!');
// source http://dev.housetrip.com/2014/09/15/decoupling-javascript-apps-using-pub-sub-pattern/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment