manan-data 0.0.0

inventyv tikv datalayer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# <img src="media/header.png" width="1000">

> Simple and modern async event emitter

<!-- [![Coverage Status](https://codecov.io/gh/sindresorhus/emittery/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/emittery) -->
[![](https://badgen.net/bundlephobia/minzip/emittery)](https://bundlephobia.com/result?p=emittery)

It works in Node.js and the browser (using a bundler).

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.

## Install

```sh
npm install emittery
```

## Usage

```js
import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on('🦄', data => {
	console.log(data);
});

const myUnicorn = Symbol('🦄');

emitter.on(myUnicorn, data => {
	console.log(`Unicorns love ${data}`);
});

emitter.emit('🦄', '🌈'); // Will trigger printing '🌈'
emitter.emit(myUnicorn, '🦋');  // Will trigger printing 'Unicorns love 🦋'
```

## API

### eventName

Emittery accepts strings, symbols, and numbers as event names.

Symbol event names are preferred given that they can be used to avoid name collisions when your classes are extended, especially for internal events.

### isDebugEnabled

Toggle debug mode for all instances.

Default: `true` if the `DEBUG` environment variable is set to `emittery` or `*`, otherwise `false`.

Example:

```js
import Emittery from 'emittery';

Emittery.isDebugEnabled = true;

const emitter1 = new Emittery({debug: {name: 'myEmitter1'}});
const emitter2 = new Emittery({debug: {name: 'myEmitter2'}});

emitter1.on('test', data => {
	// …
});

emitter2.on('otherTest', data => {
	// …
});

emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter1] Event Name: test
//	data: undefined

emitter2.emit('otherTest');
//=> [16:43:20.417][emittery:subscribe][myEmitter2] Event Name: otherTest
//	data: undefined
```

### emitter = new Emittery(options?)

Create a new instance of Emittery.

#### options?

Type: `object`

Configure the new instance of Emittery.

##### debug?

Type: `object`

Configure the debugging options for this instance.

###### name

Type: `string`\
Default: `undefined`

Define a name for the instance of Emittery to use when outputting debug data.

Example:

```js
import Emittery from 'emittery';

Emittery.isDebugEnabled = true;

const emitter = new Emittery({debug: {name: 'myEmitter'}});

emitter.on('test', data => {
	// …
});

emitter.emit('test');
//=> [16:43:20.417][emittery:subscribe][myEmitter] Event Name: test
//	data: undefined
```

###### enabled?

Type: `boolean`\
Default: `false`

Toggle debug logging just for this instance.

Example:

```js
import Emittery from 'emittery';

const emitter1 = new Emittery({debug: {name: 'emitter1', enabled: true}});
const emitter2 = new Emittery({debug: {name: 'emitter2'}});

emitter1.on('test', data => {
	// …
});

emitter2.on('test', data => {
	// …
});

emitter1.emit('test');
//=> [16:43:20.417][emittery:subscribe][emitter1] Event Name: test
//	data: undefined

emitter2.emit('test');
```

###### logger?

Type: `Function(string, string, EventName?, Record<string, any>?) => void`

Default:

```js
(type, debugName, eventName, eventData) => {
	if (typeof eventData === 'object') {
		eventData = JSON.stringify(eventData);
	}

	if (typeof eventName === 'symbol' || typeof eventName === 'number') {
		eventName = eventName.toString();
	}

	const currentTime = new Date();
	const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
	console.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\n\tdata: ${eventData}`);
}
```

Function that handles debug data.

Example:

```js
import Emittery from 'emittery';

const myLogger = (type, debugName, eventName, eventData) => {
	console.log(`[${type}]: ${eventName}`);
};

const emitter = new Emittery({
	debug: {
		name: 'myEmitter',
		enabled: true,
		logger: myLogger
	}
});

emitter.on('test', data => {
	// …
});

emitter.emit('test');
//=> [subscribe]: test
```

#### on(eventName | eventName[], listener)

Subscribe to one or more events.

Returns an unsubscribe method.

Using the same listener multiple times for the same event will result in only one method call per emitted event.

```js
import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on('🦄', data => {
	console.log(data);
});

emitter.on(['🦄', '🐶'], data => {
	console.log(data);
});

emitter.emit('🦄', '🌈'); // log => '🌈' x2
emitter.emit('🐶', '🍖'); // log => '🍖'
```

##### Custom subscribable events

Emittery exports some symbols which represent "meta" events that can be passed to `Emitter.on` and similar methods.

- `Emittery.listenerAdded` - Fires when an event listener was added.
- `Emittery.listenerRemoved` - Fires when an event listener was removed.

```js
import Emittery from 'emittery';

const emitter = new Emittery();

emitter.on(Emittery.listenerAdded, ({listener, eventName}) => {
	console.log(listener);
	//=> data => {}

	console.log(eventName);
	//=> '🦄'
});

emitter.on('🦄', data => {
	// Handle data
});
```

###### Listener data

- `listener` - The listener that was added.
- `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.

Only events that are not of this type are able to trigger these events.

##### listener(data)

#### off(eventName | eventName[], listener)

Remove one or more event subscriptions.

```js
import Emittery from 'emittery';

const emitter = new Emittery();

const listener = data => {
	console.log(data);
};

emitter.on(['🦄', '🐶', '🦊'], listener);
await emitter.emit('🦄', 'a');
await emitter.emit('🐶', 'b');
await emitter.emit('🦊', 'c');
emitter.off('🦄', listener);
emitter.off(['🐶', '🦊'], listener);
await emitter.emit('🦄', 'a'); // Nothing happens
await emitter.emit('🐶', 'b'); // Nothing happens
await emitter.emit('🦊', 'c'); // Nothing happens
```

##### listener(data)

#### once(eventName | eventName[])

Subscribe to one or more events only once. It will be unsubscribed after the first event.

Returns a promise for the event data when `eventName` is emitted. This promise is extended with an `off` method.

```js
import Emittery from 'emittery';

const emitter = new Emittery();

emitter.once('🦄').then(data => {
	console.log(data);
	//=> '🌈'
});

emitter.once(['🦄', '🐶']).then(data => {
	console.log(data);
});

emitter.emit('🦄', '🌈'); // Log => '🌈' x2
emitter.emit('🐶', '🍖'); // Nothing happens
```

#### events(eventName)

Get an async iterator which buffers data each time an event is emitted.

Call `return()` on the iterator to remove the subscription.

```js
import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events('🦄');

emitter.emit('🦄', '🌈1'); // Buffered
emitter.emit('🦄', '🌈2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '🌈1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '🌈2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});
```

In practice, you would usually consume the events using the [for await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) statement. In that case, to revoke the subscription simply break the loop.

```js
import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events('🦄');

emitter.emit('🦄', '🌈1'); // Buffered
emitter.emit('🦄', '🌈2'); // Buffered

// In an async context.
for await (const data of iterator) {
	if (data === '🌈2') {
		break; // Revoke the subscription when we see the value '🌈2'.
	}
}
```

It accepts multiple event names.

```js
import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.events(['🦄', '🦊']);

emitter.emit('🦄', '🌈1'); // Buffered
emitter.emit('🦊', '🌈2'); // Buffered

iterator
	.next()
	.then(({value, done}) => {
		// done === false
		// value === '🌈1'
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value === '🌈2'
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});
```

#### emit(eventName, data?)

Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but executed concurrently.

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.

#### emitSerial(eventName, data?)

Same as above, 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.

If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will *not* be called.

#### onAny(listener)

Subscribe to be notified about any event.

Returns a method to unsubscribe.

##### listener(eventName, data)

#### offAny(listener)

Remove an `onAny` subscription.

#### anyEvent()

Get an async iterator which buffers a tuple of an event name and data each time an event is emitted.

Call `return()` on the iterator to remove the subscription.

```js
import Emittery from 'emittery';

const emitter = new Emittery();
const iterator = emitter.anyEvent();

emitter.emit('🦄', '🌈1'); // Buffered
emitter.emit('🌟', '🌈2'); // Buffered

iterator.next()
	.then(({value, done}) => {
		// done === false
		// value is ['🦄', '🌈1']
		return iterator.next();
	})
	.then(({value, done}) => {
		// done === false
		// value is ['🌟', '🌈2']
		// Revoke subscription
		return iterator.return();
	})
	.then(({done}) => {
		// done === true
	});
```

In the same way as for `events`, you can subscribe by using the `for await` statement

#### clearListeners(eventNames?)

Clear all event listeners on the instance.

If `eventNames` is given, only the listeners for that events are cleared.

#### listenerCount(eventNames?)

The number of listeners for the `eventNames` or all events if not specified.

#### bindMethods(target, methodNames?)

Bind the given `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the `target` object.

```js
import Emittery from 'emittery';

const object = {};

new Emittery().bindMethods(object);

object.emit('event');
```

## TypeScript

The default `Emittery` class has generic types that can be provided by TypeScript users to strongly type the list of events and the data passed to their event listeners.

```ts
import Emittery from 'emittery';

const emitter = new Emittery<
	// Pass `{[eventName]: undefined | <eventArg>}` as the first type argument for events that pass data to their listeners.
	// A value of `undefined` in this map means the event listeners should expect no data, and a type other than `undefined` means the listeners will receive one argument of that type.
	{
		open: string,
		close: undefined
	}
>();

// Typechecks just fine because the data type for the `open` event is `string`.
emitter.emit('open', 'foo\n');

// Typechecks just fine because `close` is present but points to undefined in the event data type map.
emitter.emit('close');

// TS compilation error because `1` isn't assignable to `string`.
emitter.emit('open', 1);

// TS compilation error because `other` isn't defined in the event data type map.
emitter.emit('other');
```

### Emittery.mixin(emitteryPropertyName, methodNames?)

A decorator which mixins `Emittery` as property `emitteryPropertyName` and `methodNames`, or all `Emittery` methods if `methodNames` is not defined, into the target class.

```ts
import Emittery from 'emittery';

@Emittery.mixin('emittery')
class MyClass {}

const instance = new MyClass();

instance.emit('event');
```

## Scheduling details

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.

Note that when using `.emitSerial()`, a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.

## Debugging

Emittery can collect and log debug information.

To enable this feature set the DEBUG environment variable to `'emittery'` or `'*'`. Additionally you can set the static `isDebugEnabled` variable to true on the Emittery class, or `myEmitter.debug.enabled` on an instance of it for debugging a single instance.

See [API](#api) for more details on how debugging works.

## FAQ

### How is this different than the built-in `EventEmitter` in Node.js?

There are many things to not like about `EventEmitter`: its huge API surface, synchronous event emitting, magic error event, flawed memory leak detection. Emittery has none of that.

### Isn't `EventEmitter` synchronous for a reason?

Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.

It also allows silly code like this:

```js
let unicorn = false;

emitter.on('🦄', () => {
	unicorn = true;
});

emitter.emit('🦄');

console.log(unicorn);
//=> true
```

But I would argue doing that shows a deeper lack of Node.js and async comprehension and is not something we should optimize for. The benefit of async emitting is much greater.

### Can you support multiple arguments for `emit()`?

No, just use [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):

```js
emitter.on('🦄', ([foo, bar]) => {
	console.log(foo, bar);
});

emitter.emit('🦄', [foo, bar]);
```

## Related

- [p-event]https://github.com/sindresorhus/p-event - Promisify an event by waiting for it to be emitted