Created
September 7, 2017 06:43
-
-
Save lalitrhombus/4027bb23d7dfa9d9f91dda9a190e389a to your computer and use it in GitHub Desktop.
Travel Triangle Interview Round
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
| // Create an event bus | |
| function Bus() { | |
| let eventFuncObject={}; | |
| function on(eventName, eventFunc){ | |
| if(!eventFuncObject[eventName]){ | |
| eventFuncObject[eventName]=[]; | |
| } | |
| eventFuncObject[eventName].push(eventFunc); | |
| } | |
| function off(eventName){ | |
| delete eventFuncObject[eventName]; | |
| } | |
| function trigger(eventName){ | |
| let argumetsArry = []; | |
| eventFuncObject[eventName].map(eventFunc=>{ | |
| Object.keys(arguments).map(argKey=>{ | |
| if(argKey !== '0'){ | |
| argumetsArry.push(arguments[argKey]); | |
| } | |
| }) | |
| eventFunc(...argumetsArry); | |
| }); | |
| } | |
| this.on = on; | |
| this.off = off; | |
| this.trigger = trigger; | |
| } | |
| var handler = new Bus(); | |
| handler.on('click', function () { | |
| console.log('on click was triggered'); | |
| }) | |
| handler.on('click', function () { | |
| console.log('another handler'); | |
| }) | |
| handler.on('sum', function (a, b) { | |
| var sum = a + b; | |
| console.log(sum); | |
| }); | |
| handler.trigger('click'); | |
| // console.log's 2 statements | |
| handler.off('click'); | |
| // handler.trigger('click'); | |
| handler.trigger('sum',3,4,5); | |
| handler.trigger('sum',3,8,5,5); | |
| // nothing happens |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment