Last active
February 16, 2017 13:14
-
-
Save kevjose/adda6e753b140f9b47c87c35d8b09e14 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
| function CreateEventBus () { | |
| this._listeners = {} // to store the events key being the event name and value being the function to be called | |
| } | |
| CreateEventBus.prototype = { | |
| constructor: CreateEventBus, | |
| on: function(type, listener) { | |
| if(this._listeners[type] === undefined){ | |
| this._listeners[type] = []; // to handle multiple funcitons on the same event | |
| } | |
| this._listeners[type].push(listener); | |
| }, | |
| trigger: function() { | |
| if(!arguments[0]) throw new Error; | |
| if(this._listeners[arguments[0]] instanceof Array){ | |
| var listeners = this._listeners[arguments[0]]; | |
| for(var i= 0; i< listeners.length; i++) | |
| listeners[i].call(this, arguments); // executing the callback | |
| } | |
| }, | |
| off: function(type, listener) { | |
| delete this._listeners[type]; // deletes the event | |
| } | |
| }; | |
| var obj = new CreateEventBus(); // to add on, trigger, off methods | |
| obj.on("Hello", function(){ | |
| console.log("Hello"); | |
| }); | |
| obj.trigger("Hello"); | |
| obj.off("Hello"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment