Skip to content

Instantly share code, notes, and snippets.

@hunje
Last active December 3, 2020 12:09
Show Gist options
  • Save hunje/f7312f081bc1f02683182aac2922f941 to your computer and use it in GitHub Desktop.
Save hunje/f7312f081bc1f02683182aac2922f941 to your computer and use it in GitHub Desktop.
simple event emitter
/**
* Declare Simple EventEmitter
* No Limitation, No expandable.
* If you need to implement more or genric, please contact hunje
*/
type EventHandlerMap = {
[key:string]:Function[];
}
class EventEmitter {
private eventHandlers:EventHandlerMap = {};
private eventOnceHanders:EventHandlerMap = {};
public addListener(type:string, handler:Function) {
const handlers = this.eventHandlers[type];
if (!handlers) {
this.eventHandlers[type] = [handler];
} else {
this.eventHandlers[type].push(handler);
}
}
public runOnce(type:string, handler:Function) {
const handlers = this.eventOnceHanders[type];
if (!handlers) {
this.eventOnceHanders[type] = [handler];
} else {
this.eventOnceHanders[type].push(handler);
}
}
public removeListener(type:string, handler:Function) {
if (type in this.eventHandlers) {
const index = this.eventHandlers[type].indexOf(handler);
if (index >= 0) {
this.eventHandlers[type].splice(index, 1);
}
}
if (type in this.eventOnceHanders) {
const index = this.eventOnceHanders[type].indexOf(handler);
if (index >= 0) {
this.eventOnceHanders[type].splice(index, 1);
}
}
}
public removeListeners(type:string) {
if (type in this.eventHandlers) {
this.eventHandlers[type] = [];
this.eventOnceHanders[type] = [];
}
}
public emit(type:string) {
if (this.eventHandlers[type]) {
for (const handler of this.eventHandlers[type]) {
handler();
}
}
this.once(type);
}
private once(type:string) {
const handlers = this.eventOnceHanders[type];
this.eventOnceHanders[type] = [];
if (handlers) {
for (const handler of handlers) {
handler();
}
}
}
}
export {
EventEmitter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment