emittery 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /**
2
+ Emittery accepts strings and symbols as event names.
3
+
4
+ Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.
5
+ */
6
+ type EventName = string | symbol;
7
+
1
8
  declare class Emittery {
2
9
  /**
3
10
  In TypeScript, it returns a decorator which mixins `Emittery` as property `emitteryPropertyName` and `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the target class.
@@ -16,6 +23,60 @@ declare class Emittery {
16
23
  */
17
24
  static mixin(emitteryPropertyName: string, methodNames?: readonly string[]): Function;
18
25
 
26
+ /**
27
+ Fires when an event listener was added.
28
+
29
+ An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
30
+
31
+ @example
32
+ ```
33
+ import Emittery = require('emittery');
34
+
35
+ const emitter = new Emittery();
36
+
37
+ emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
38
+ console.log(listener);
39
+ //=> data => {}
40
+
41
+ console.log(eventName);
42
+ //=> '🦄'
43
+ });
44
+
45
+ emitter.on('🦄', data => {
46
+ // Handle data
47
+ });
48
+ ```
49
+ */
50
+ static readonly listenerAdded: unique symbol;
51
+
52
+ /**
53
+ Fires when an event listener was removed.
54
+
55
+ An object with `listener` and `eventName` (if `on` or `off` was used) is provided as event data.
56
+
57
+ @example
58
+ ```
59
+ import Emittery = require('emittery');
60
+
61
+ const emitter = new Emittery();
62
+
63
+ const off = emitter.on('🦄', data => {
64
+ // Handle data
65
+ });
66
+
67
+ emitter.on(Emittery.listenerRemoved, ({listener, eventName}) => {
68
+ console.log(listener);
69
+ //=> data => {}
70
+
71
+ console.log(eventName);
72
+ //=> '🦄'
73
+ });
74
+
75
+ off();
76
+ ```
77
+ */
78
+ static readonly listenerRemoved: unique symbol;
79
+
19
80
  /**
20
81
  Subscribe to an event.
21
82
 
@@ -23,7 +84,8 @@ declare class Emittery {
23
84
 
24
85
  @returns An unsubscribe method.
25
86
  */
26
- on(eventName: string, listener: (eventData?: unknown) => void): Emittery.UnsubscribeFn;
87
+ on(eventName: typeof Emittery.listenerAdded | typeof Emittery.listenerRemoved, listener: (eventData: Emittery.ListenerChangedData) => void): Emittery.UnsubscribeFn
88
+ on(eventName: EventName, listener: (eventData?: unknown) => void): Emittery.UnsubscribeFn;
27
89
 
28
90
  /**
29
91
  Get an async iterator which buffers data each time an event is emitted.
@@ -78,12 +140,12 @@ declare class Emittery {
78
140
  }
79
141
  ```
80
142
  */
81
- events(eventName:string): AsyncIterableIterator<unknown>
143
+ events(eventName: EventName): AsyncIterableIterator<unknown>
82
144
 
83
145
  /**
84
146
  Remove an event subscription.
85
147
  */
86
- off(eventName: string, listener: (eventData?: unknown) => void): void;
148
+ off(eventName: EventName, listener: (eventData?: unknown) => void): void;
87
149
 
88
150
  /**
89
151
  Subscribe to an event only once. It will be unsubscribed after the first
@@ -91,14 +153,15 @@ declare class Emittery {
91
153
 
92
154
  @returns The event data when `eventName` is emitted.
93
155
  */
94
- once(eventName: string): Promise<unknown>;
156
+ once(eventName: typeof Emittery.listenerAdded | typeof Emittery.listenerRemoved): Promise<Emittery.ListenerChangedData>
157
+ once(eventName: EventName): Promise<unknown>;
95
158
 
96
159
  /**
97
160
  Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.
98
161
 
99
162
  @returns A promise that resolves when all the event listeners are done. *Done* meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
100
163
  */
101
- emit(eventName: string, eventData?: unknown): Promise<void>;
164
+ emit(eventName: EventName, eventData?: unknown): Promise<void>;
102
165
 
103
166
  /**
104
167
  Same as `emit()`, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer `emit()` whenever possible.
@@ -107,14 +170,14 @@ declare class Emittery {
107
170
 
108
171
  @returns A promise that resolves when all the event listeners are done.
109
172
  */
110
- emitSerial(eventName: string, eventData?: unknown): Promise<void>;
173
+ emitSerial(eventName: EventName, eventData?: unknown): Promise<void>;
111
174
 
112
175
  /**
113
176
  Subscribe to be notified about any event.
114
177
 
115
178
  @returns A method to unsubscribe.
116
179
  */
117
- onAny(listener: (eventName: string, eventData?: unknown) => unknown): Emittery.UnsubscribeFn;
180
+ onAny(listener: (eventName: EventName, eventData?: unknown) => unknown): Emittery.UnsubscribeFn;
118
181
 
119
182
  /**
120
183
  Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.
@@ -155,19 +218,19 @@ declare class Emittery {
155
218
  /**
156
219
  Remove an `onAny` subscription.
157
220
  */
158
- offAny(listener: (eventName: string, eventData?: unknown) => void): void;
221
+ offAny(listener: (eventName: EventName, eventData?: unknown) => void): void;
159
222
 
160
223
  /**
161
224
  Clear all event listeners on the instance.
162
225
 
163
226
  If `eventName` is given, only the listeners for that event are cleared.
164
227
  */
165
- clearListeners(eventName?: string): void;
228
+ clearListeners(eventName?: EventName): void;
166
229
 
167
230
  /**
168
231
  The number of listeners for the `eventName` or all events if not specified.
169
232
  */
170
- listenerCount(eventName?: string): number;
233
+ listenerCount(eventName?: EventName): number;
171
234
 
172
235
  /**
173
236
  Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.
@@ -191,12 +254,29 @@ declare namespace Emittery {
191
254
  Removes an event subscription.
192
255
  */
193
256
  type UnsubscribeFn = () => void;
257
+ type EventNameFromDataMap<EventDataMap> = Extract<keyof EventDataMap, EventName>;
194
258
 
195
259
  /**
196
260
  Maps event names to their emitted data type.
197
261
  */
198
262
  interface Events {
199
- [eventName: string]: any;
263
+ // Blocked by https://github.com/microsoft/TypeScript/issues/1863, should be
264
+ // `[eventName: EventName]: unknown;`
265
+ }
266
+
267
+ /**
268
+ The data provided as `eventData` when listening for `Emittery.listenerAdded` or `Emittery.listenerRemoved`.
269
+ */
270
+ interface ListenerChangedData {
271
+ /**
272
+ The listener that was added or removed.
273
+ */
274
+ listener: (eventData?: unknown) => void;
275
+
276
+ /**
277
+ The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
278
+ */
279
+ eventName?: EventName;
200
280
  }
201
281
 
202
282
  /**
@@ -216,27 +296,27 @@ declare namespace Emittery {
216
296
  emitter.emit('end'); // TS compilation error
217
297
  ```
218
298
  */
219
- class Typed<EventDataMap extends Events, EmptyEvents extends string = never> extends Emittery {
220
- on<Name extends Extract<keyof EventDataMap, string>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): Emittery.UnsubscribeFn;
299
+ class Typed<EventDataMap extends Events, EmptyEvents extends EventName = never> extends Emittery {
300
+ on<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): Emittery.UnsubscribeFn;
221
301
  on<Name extends EmptyEvents>(eventName: Name, listener: () => void): Emittery.UnsubscribeFn;
222
302
 
223
- events<Name extends Extract<keyof EventDataMap, string>>(eventName: Name): AsyncIterableIterator<EventDataMap[Name]>;
303
+ events<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name): AsyncIterableIterator<EventDataMap[Name]>;
224
304
 
225
- once<Name extends Extract<keyof EventDataMap, string>>(eventName: Name): Promise<EventDataMap[Name]>;
305
+ once<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name): Promise<EventDataMap[Name]>;
226
306
  once<Name extends EmptyEvents>(eventName: Name): Promise<void>;
227
307
 
228
- off<Name extends Extract<keyof EventDataMap, string>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): void;
308
+ off<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, listener: (eventData: EventDataMap[Name]) => void): void;
229
309
  off<Name extends EmptyEvents>(eventName: Name, listener: () => void): void;
230
310
 
231
- onAny(listener: (eventName: Extract<keyof EventDataMap, string> | EmptyEvents, eventData?: EventDataMap[Extract<keyof EventDataMap, string>]) => void): Emittery.UnsubscribeFn;
232
- anyEvent(): AsyncIterableIterator<[Extract<keyof EventDataMap, string>, EventDataMap[Extract<keyof EventDataMap, string>]]>;
311
+ onAny(listener: (eventName: EventNameFromDataMap<EventDataMap> | EmptyEvents, eventData?: EventDataMap[EventNameFromDataMap<EventDataMap>]) => void): Emittery.UnsubscribeFn;
312
+ anyEvent(): AsyncIterableIterator<[EventNameFromDataMap<EventDataMap>, EventDataMap[EventNameFromDataMap<EventDataMap>]]>;
233
313
 
234
- offAny(listener: (eventName: Extract<keyof EventDataMap, string> | EmptyEvents, eventData?: EventDataMap[Extract<keyof EventDataMap, string>]) => void): void;
314
+ offAny(listener: (eventName: EventNameFromDataMap<EventDataMap> | EmptyEvents, eventData?: EventDataMap[EventNameFromDataMap<EventDataMap>]) => void): void;
235
315
 
236
- emit<Name extends Extract<keyof EventDataMap, string>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
316
+ emit<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
237
317
  emit<Name extends EmptyEvents>(eventName: Name): Promise<void>;
238
318
 
239
- emitSerial<Name extends Extract<keyof EventDataMap, string>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
319
+ emitSerial<Name extends EventNameFromDataMap<EventDataMap>>(eventName: Name, eventData: EventDataMap[Name]): Promise<void>;
240
320
  emitSerial<Name extends EmptyEvents>(eventName: Name): Promise<void>;
241
321
  }
242
322
  }
package/index.js CHANGED
@@ -6,9 +6,12 @@ const producersMap = new WeakMap();
6
6
  const anyProducer = Symbol('anyProducer');
7
7
  const resolvedPromise = Promise.resolve();
8
8
 
9
+ const listenerAdded = Symbol('listenerAdded');
10
+ const listenerRemoved = Symbol('listenerRemoved');
11
+
9
12
  function assertEventName(eventName) {
10
- if (typeof eventName !== 'string') {
11
- throw new TypeError('eventName must be a string');
13
+ if (typeof eventName !== 'string' && typeof eventName !== 'symbol') {
14
+ throw new TypeError('eventName must be a string or a symbol');
12
15
  }
13
16
  }
14
17
 
@@ -134,6 +137,8 @@ function defaultMethodNamesOrAssert(methodNames) {
134
137
  return methodNames;
135
138
  }
136
139
 
140
+ const isListenerSymbol = symbol => symbol === listenerAdded || symbol === listenerRemoved;
141
+
137
142
  class Emittery {
138
143
  static mixin(emitteryPropertyName, methodNames) {
139
144
  methodNames = defaultMethodNamesOrAssert(methodNames);
@@ -186,12 +191,22 @@ class Emittery {
186
191
  assertEventName(eventName);
187
192
  assertListener(listener);
188
193
  getListeners(this, eventName).add(listener);
194
+
195
+ if (!isListenerSymbol(eventName)) {
196
+ this.emit(listenerAdded, {eventName, listener});
197
+ }
198
+
189
199
  return this.off.bind(this, eventName, listener);
190
200
  }
191
201
 
192
202
  off(eventName, listener) {
193
203
  assertEventName(eventName);
194
204
  assertListener(listener);
205
+
206
+ if (!isListenerSymbol(eventName)) {
207
+ this.emit(listenerRemoved, {eventName, listener});
208
+ }
209
+
195
210
  getListeners(this, eventName).delete(listener);
196
211
  }
197
212
 
@@ -218,7 +233,7 @@ class Emittery {
218
233
  const listeners = getListeners(this, eventName);
219
234
  const anyListeners = anyMap.get(this);
220
235
  const staticListeners = [...listeners];
221
- const staticAnyListeners = [...anyListeners];
236
+ const staticAnyListeners = isListenerSymbol(eventName) ? [] : [...anyListeners];
222
237
 
223
238
  await resolvedPromise;
224
239
  return Promise.all([
@@ -262,6 +277,7 @@ class Emittery {
262
277
  onAny(listener) {
263
278
  assertListener(listener);
264
279
  anyMap.get(this).add(listener);
280
+ this.emit(listenerAdded, {listener});
265
281
  return this.offAny.bind(this, listener);
266
282
  }
267
283
 
@@ -271,6 +287,7 @@ class Emittery {
271
287
 
272
288
  offAny(listener) {
273
289
  assertListener(listener);
290
+ this.emit(listenerRemoved, {listener});
274
291
  anyMap.get(this).delete(listener);
275
292
  }
276
293
 
@@ -354,4 +371,17 @@ Object.defineProperty(Emittery.Typed, 'Typed', {
354
371
  value: undefined
355
372
  });
356
373
 
374
+ Object.defineProperty(Emittery, 'listenerAdded', {
375
+ value: listenerAdded,
376
+ writable: false,
377
+ enumerable: true,
378
+ configurable: false
379
+ });
380
+ Object.defineProperty(Emittery, 'listenerRemoved', {
381
+ value: listenerRemoved,
382
+ writable: false,
383
+ enumerable: true,
384
+ configurable: false
385
+ });
386
+
357
387
  module.exports = Emittery;
package/license CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
6
 
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "emittery",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Simple and modern async event emitter",
5
5
  "license": "MIT",
6
6
  "repository": "sindresorhus/emittery",
7
+ "funding": "https://github.com/sindresorhus/emittery?sponsor=1",
7
8
  "author": {
8
9
  "name": "Sindre Sorhus",
9
10
  "email": "sindresorhus@gmail.com",
10
- "url": "sindresorhus.com"
11
+ "url": "https://sindresorhus.com"
11
12
  },
12
13
  "engines": {
13
- "node": ">=8"
14
+ "node": ">=10"
14
15
  },
15
16
  "scripts": {
16
17
  "test": "xo && nyc ava && tsd"
@@ -47,13 +48,14 @@
47
48
  "typed"
48
49
  ],
49
50
  "devDependencies": {
50
- "@types/node": "^12.7.5",
51
+ "@types/node": "^13.7.5",
51
52
  "ava": "^2.4.0",
52
53
  "codecov": "^3.1.0",
53
54
  "delay": "^4.3.0",
54
- "nyc": "^14.1.1",
55
- "tsd": "^0.7.4",
56
- "xo": "^0.24.0"
55
+ "nyc": "^15.0.0",
56
+ "p-event": "^4.1.0",
57
+ "tsd": "^0.11.0",
58
+ "xo": "^0.25.4"
57
59
  },
58
60
  "nyc": {
59
61
  "reporter": [
package/readme.md CHANGED
@@ -2,22 +2,18 @@
2
2
 
3
3
  > Simple and modern async event emitter
4
4
 
5
- [![Build Status](https://travis-ci.org/sindresorhus/emittery.svg?branch=master)](https://travis-ci.org/sindresorhus/emittery) [![codecov](https://codecov.io/gh/sindresorhus/emittery/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery)
6
-
7
- It's only ~200 bytes minified and gzipped. [I'm not fanatic about keeping the size at this level though.](https://github.com/sindresorhus/emittery/pull/5#issuecomment-347479211)
5
+ [![Build Status](https://travis-ci.org/sindresorhus/emittery.svg?branch=master)](https://travis-ci.org/sindresorhus/emittery) [![codecov](https://codecov.io/gh/sindresorhus/emittery/branch/master/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery) [![](https://badgen.net/bundlephobia/minzip/emittery)](https://bundlephobia.com/result?p=emittery)
8
6
 
9
7
  It works in Node.js and the browser (using a bundler).
10
8
 
11
9
  Emitting events asynchronously is important for production code where you want the least amount of synchronous operations. Since JavaScript is single-threaded, no other code can run while doing synchronous operations. For Node.js, that means it will block other requests, defeating the strength of the platform, which is scalability through async. In the browser, a synchronous operation could potentially cause lags and block user interaction.
12
10
 
13
-
14
11
  ## Install
15
12
 
16
13
  ```
17
14
  $ npm install emittery
18
15
  ```
19
16
 
20
-
21
17
  ## Usage
22
18
 
23
19
  ```js
@@ -27,15 +23,26 @@ const emitter = new Emittery();
27
23
 
28
24
  emitter.on('🦄', data => {
29
25
  console.log(data);
30
- // '🌈'
31
26
  });
32
27
 
33
- emitter.emit('🦄', '🌈');
34
- ```
28
+ const myUnicorn = Symbol('🦄');
35
29
 
30
+ emitter.on(myUnicorn, data => {
31
+ console.log(`Unicorns love ${data}`);
32
+ });
33
+
34
+ emitter.emit('🦄', '🌈'); // Will trigger printing '🌈'
35
+ emitter.emit(myUnicorn, '🦋'); // Will trigger printing 'Unicorns love 🦋'
36
+ ```
36
37
 
37
38
  ## API
38
39
 
40
+ ### eventName
41
+
42
+ Emittery accepts strings and symbols as event names.
43
+
44
+ Symbol event names can be used to avoid name collisions when your classes are extended, especially for internal events.
45
+
39
46
  ### emitter = new Emittery()
40
47
 
41
48
  #### on(eventName, listener)
@@ -46,6 +53,38 @@ Returns an unsubscribe method.
46
53
 
47
54
  Using the same listener multiple times for the same event will result in only one method call per emitted event.
48
55
 
56
+ ##### Custom subscribable events
57
+
58
+ Emittery exports some symbols which represent custom events that can be passed to `Emitter.on` and similar methods.
59
+
60
+ - `Emittery.listenerAdded` - Fires when an event listener was added.
61
+ - `Emittery.listenerRemoved` - Fires when an event listener was removed.
62
+
63
+ ```js
64
+ const Emittery = require('emittery');
65
+
66
+ const emitter = new Emittery();
67
+
68
+ emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
69
+ console.log(listener);
70
+ //=> data => {}
71
+
72
+ console.log(eventName);
73
+ //=> '🦄'
74
+ });
75
+
76
+ emitter.on('🦄', data => {
77
+ // Handle data
78
+ });
79
+ ```
80
+
81
+ ###### Listener data
82
+
83
+ - `listener` - The listener that was added.
84
+ - `eventName` - The name of the event that was added or removed if `.on()` or `.off()` was used, or `undefined` if `.onAny()` or `.offAny()` was used.
85
+
86
+ Only events that are not of this type are able to trigger these events.
87
+
49
88
  ##### listener(data)
50
89
 
51
90
  #### off(eventName, listener)
@@ -207,7 +246,6 @@ new Emittery().bindMethods(object);
207
246
  object.emit('event');
208
247
  ```
209
248
 
210
-
211
249
  ## TypeScript
212
250
 
213
251
  The default `Emittery` class does not let you type allowed event names and their associated data. However, you can use `Emittery.Typed` with generics:
@@ -238,14 +276,12 @@ const instance = new MyClass();
238
276
  instance.emit('event');
239
277
  ```
240
278
 
241
-
242
279
  ## Scheduling details
243
280
 
244
281
  Listeners are not invoked for events emitted *before* the listener was added. Removing a listener will prevent that listener from being invoked, even if events are in the process of being (asynchronously!) emitted. This also applies to `.clearListeners()`, which removes all listeners. Listeners will be called in the order they were added. So-called *any* listeners are called *after* event-specific listeners.
245
282
 
246
283
  Note that when using `.emitSerial()`, a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.
247
284
 
248
-
249
285
  ## FAQ
250
286
 
251
287
  ### How is this different than the built-in `EventEmitter` in Node.js?
@@ -285,7 +321,6 @@ emitter.on('🦄', ([foo, bar]) => {
285
321
  emitter.emit('🦄', [foo, bar]);
286
322
  ```
287
323
 
288
-
289
324
  ## Related
290
325
 
291
326
  - [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted