Skip to content

Commit

Permalink
Use @servie/events
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey committed Jun 12, 2019
1 parent 3b96fb2 commit 525c1ce
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 65 deletions.
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"typescript": "^3.4.1"
},
"dependencies": {
"@servie/events": "^1.0.0",
"byte-length": "^1.0.2"
}
}
68 changes: 3 additions & 65 deletions src/signal.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,4 @@
/**
* Event listener type.
*/
type EventListener<T, K extends keyof T> = (
...args: (T & Record<PropertyKey, any[]>)[K]
) => void;

/**
* Wildcard event listener type.
*/
type EachEventListener<T> = {
[K in keyof T]: (
type: K,
...args: (T & Record<PropertyKey, any[]>)[K]
) => void
}[keyof T];

/**
* Type-safe event emitter.
*/
class Events<T> {
all: Array<EachEventListener<T>> = [];
any: { [K in keyof T]: Array<EventListener<T, K>> } = Object.create(null);

on<K extends keyof T>(type: K, callback: EventListener<T, K>) {
(this.any[type] = this.any[type] || []).push(callback);
}

off<K extends keyof T>(type: K, callback: EventListener<T, K>) {
const stack = this.any[type] || [];
stack.splice(stack.indexOf(callback) >>> 0, 1);
}

each(callback: EachEventListener<T>) {
this.all.push(callback);
}

none(callback: EachEventListener<T>) {
this.all.splice(this.all.indexOf(callback) >>> 0, 1);
}

emit<K extends keyof T>(
type: K,
...args: (T & Record<PropertyKey, any[]>)[K]
) {
(this.any[type] || []).slice().forEach(fn => fn(...args));
this.all.slice().forEach(fn => fn(type, ...args));
}
}

/**
* Helper to listen to an event once only.
*/
function once<T, K extends keyof T>(
e: Events<T>,
type: K,
callback: EventListener<T, K>
) {
return e.on(type, function once(...args) {
e.off(type, once);
callback(...args);
});
}
import { Emitter } from "@servie/events";

/**
* Dictionary of supported signal events.
Expand All @@ -78,14 +16,14 @@ export interface SignalEvents {
/**
* Standard signal used to communicate during `request` processing.
*/
export class Signal extends Events<SignalEvents> {
export class Signal extends Emitter<SignalEvents> {
aborted = false;

constructor() {
super();

// Listen for the abort signal.
once(this, "abort", () => (this.aborted = true));
this.on("abort", () => (this.aborted = true));
}
}

Expand Down

0 comments on commit 525c1ce

Please sign in to comment.