Last active
December 3, 2020 12:09
-
-
Save hunje/f7312f081bc1f02683182aac2922f941 to your computer and use it in GitHub Desktop.
simple event emitter
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
/** | |
* 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