Revenge/src/lib/emitter.ts
redstonekasi 4c9fe8fcaf
[Storage] Rework everything (#10)
* [storage] rework everything

* [storage] expose createProxy

* [storage] add useProxy hook

* [storage] fix settings.ts

* [Storage] Implement wrapSync, fix UI

* [storage] fix storage

* [plugins] re-add plugin loading

* [storage] fix fix storage

* [storage] make wrapSync more magical

* [storage] save deletes

* [ui] hack around plugin removal... again

* [plugins] make plugin storage work

* [storage] expose api

---------

Co-authored-by: Beef <beefers@riseup.net>
2023-01-29 21:05:47 +00:00

35 lines
1 KiB
TypeScript

import { Emitter, EmitterEvent, EmitterListener, EmitterListenerData, EmitterListeners } from "@types";
export const Events = Object.freeze({
GET: "GET",
SET: "SET",
DEL: "DEL"
});
export default function createEmitter(): Emitter {
return {
listeners: Object.values(Events).reduce<EmitterListeners>((acc, val: string) => ((acc[val] = new Set<EmitterListener>()), acc), {}) as EmitterListeners,
on(event: EmitterEvent, listener: EmitterListener) {
if (!this.listeners[event].has(listener))
this.listeners[event].add(listener);
},
off(event: EmitterEvent, listener: EmitterListener) {
this.listeners[event].delete(listener);
},
once(event: EmitterEvent, listener: EmitterListener) {
const once = (event: EmitterEvent, data: EmitterListenerData) => {
this.off(event, once);
listener(event, data);
}
this.on(event, once);
},
emit(event: EmitterEvent, data: EmitterListenerData) {
for (const listener of this.listeners[event])
listener(event, data);
},
};
}