Created
February 24, 2019 06:42
-
-
Save kumaraksi/e0c4506497efee85fb467bc72a2f5db7 to your computer and use it in GitHub Desktop.
EventBus
This file contains 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
export class EventBus{ | |
static instance; | |
constructor(){ | |
if(EventBus.instance){ | |
return EventBus.instance | |
} | |
this.subscribers = []; | |
EventBus.instance = this; | |
} | |
static getInstance(){ | |
return new EventBus(); | |
} | |
subscribe(eventName,handler){ | |
const eventHanlder = { | |
event:eventName, | |
handler:handler | |
} | |
this.subscribers.push(eventHanlder) | |
} | |
emit(eventName,payload){ | |
for(const subscriber of this.subscribers){ | |
if(subscriber.event === eventName){ | |
subscriber.handler(payload); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment