Created
November 13, 2017 07:50
-
-
Save saiumesh535/df0cf5f8dc615afbef2948d75c1a0a24 to your computer and use it in GitHub Desktop.
Writing custom emitter's in nodejs
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
| // let's code some emitters | |
| function Emitter(){ | |
| this.events = {}; | |
| } | |
| const emtr = new Emitter(); | |
| // on function to push events in array | |
| Emitter.prototype.on = function(type,listener){ | |
| this.events[type] = this.events[type] || []; | |
| this.events[type].push(listener); | |
| } | |
| // when you want to emit | |
| Emitter.prototype.emit = function(type){ | |
| if(this.events[type]){ | |
| this.events[type].forEach(listener => { | |
| listener(); | |
| }); | |
| } | |
| } | |
| // adding events to array | |
| emtr.on("Namastey",()=>{ | |
| console.log("That's Hi in Hindi"); | |
| }) | |
| // emitting the events | |
| emtr.emit("Namastey"); // this will print console | |
| emtr.emit("Sss"); // and this won't |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment