Skip to content

Commit

Permalink
feat: document EventEmitter class for that perfect JSR score :D
Browse files Browse the repository at this point in the history
  • Loading branch information
eliassjogreen committed Mar 3, 2024
1 parent d8e466e commit 45f4b0b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
2 changes: 1 addition & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@denosaurs/event",
"version": "2.0.1",
"version": "2.0.2",
"exports": "./mod.ts"
}
54 changes: 53 additions & 1 deletion mod.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* # Event
*
* Strictly typed event emitter with asynciterator support.
* Strictly typed event emitter with {@link Symbol.asyncIterator} support.
*
* Events should be defined as a literal object type where the key is the event
* name, and the value is a tuple with any amount of elements of any type.
Expand Down Expand Up @@ -79,6 +79,58 @@ type Entry<E, K extends keyof E> = {
const isNullish = (value: unknown): value is null | undefined =>
value === null || value === undefined;

/**
* Strictly typed event emitter base class with {@link Symbol.asyncIterator} support.
*
* @example
*
* ```ts
* type Events = {
* foo: [string];
* bar: [number, boolean];
* };
*
* class MyClass extends EventEmitter<Events> {}
* const MyClassInstance = new MyClass();
*
* function listener(num, bool) {}
*
* // add a listener to the bar event
* MyClassInstance.on("bar", listener);
*
* // remove a listener from the bar event
* MyClassInstance.off("bar", listener);
*
* // remove all listeners from the bar event
* MyClassInstance.off("bar");
*
* // remove all listeners from the event emitter
* MyClassInstance.off();
*
* // add a one-time listener to the bar event
* MyClassInstance.once("bar", listener);
*
* // on, once, and off are chainable
* MyClassInstance.on("bar", listener).off("bar", listener);
*
* // emit the bar event with the wanted data
* MyClassInstance.emit("bar", 42, true);
*
* // listen to all events with an async iterator
* for await (const event of MyClassInstance) {
* if (event.name === "bar") {
* // event.value is of type [number, boolean]
* }
* }
*
* // listen to a specific event with an async iterator
* for await (const [num, bool] of MyClassInstance.on("bar")) {
* }
*
* // removes all listeners and closes async iterators
* MyClassInstance.close("bar");
* ```
*/
export class EventEmitter<E extends Record<string, unknown[]>> {
#listeners: {
[K in keyof E]?: Array<{
Expand Down

0 comments on commit 45f4b0b

Please sign in to comment.