Created
November 15, 2017 06:48
-
-
Save csclyde/4621e4cc8530e28f436a5d0687d6cc12 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
| EventRouter = function() { | |
| this.events = {}; | |
| } | |
| EventRouter.prototype.subscribe = function(eventName, callback, context) { | |
| if(!this.events[eventName]) { | |
| this.events[eventName] = []; | |
| } | |
| this.events[eventName].push({func: callback, ctx: context}); | |
| }; | |
| EventRouter.prototype.publish = function(eventName, parameters) { | |
| if(!this.events[eventName]) { | |
| console.log('Event published with no lsiteners: ' + eventName); | |
| return; | |
| } | |
| this.events[eventName].forEach(function(el) { | |
| el.func.apply(el.ctx, [parameters || {}]); | |
| }); | |
| }; | |
| EventRouter.prototype.unsubscribe = function(eventName, callback) { | |
| if(!this.events[eventName]){ | |
| return; | |
| } | |
| //filter out the method to be removed | |
| this.events[eventName] = this.events[eventName].filter(function(el) { | |
| return el !== callback; | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment