Created
March 15, 2017 13:25
-
-
Save evaldosantos/7982de8e1f30fc53e386743c6347d27f to your computer and use it in GitHub Desktop.
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 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