Last active
March 1, 2018 18:50
-
-
Save benstevinson/a40b88289feee8c03155fdbc0947d51b to your computer and use it in GitHub Desktop.
TypeScript Event Dispatcher
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
class ReactorEvent { | |
private name: string; | |
public callbacks: Function[]; | |
constructor (name: string) { | |
this.name = name; | |
this.callbacks = []; | |
} | |
public addCallback(cb: Function) { | |
this.callbacks.push(cb); | |
} | |
} | |
interface IReactorEvents { | |
[key: string]: ReactorEvent; | |
} | |
export default class Reactor { | |
private events: IReactorEvents; | |
constructor() { | |
this.events = {}; | |
} | |
public addEventListener(eventName: string, cb: Function) { | |
let rEvent = this.events[eventName]; | |
if (!rEvent) { | |
rEvent = new ReactorEvent(eventName); | |
} | |
rEvent.addCallback(cb); | |
this.events[eventName] = rEvent; | |
} | |
public dispatchEvent(eventName: string, eventDetails?: object) { | |
for (let cb of this.events[eventName].callbacks) { | |
cb(eventDetails); | |
} | |
} | |
public clearEvent(eventName) { | |
delete(this.events[eventName]); | |
} | |
} | |
// Usage Example: | |
// const r = new Reactor(); | |
// r.addEventListener('testEvent', (optionalEventDetails) => console.log("testEvent Fired", optionalEventDetails)) | |
// r.dispatchEvent('testEvent', {thisObjectIsOptional: true}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment