UNPKG

2.39 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/api authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import EventEmitter from 'eventemitter3';
4export class Events {
5 #eventemitter = new EventEmitter();
6
7 emit(type, ...args) {
8 return this.#eventemitter.emit(type, ...args);
9 }
10 /**
11 * @description Attach an eventemitter handler to listen to a specific event
12 *
13 * @param type The type of event to listen to. Available events are `connected`, `disconnected`, `ready` and `error`
14 * @param handler The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.
15 *
16 * @example
17 * <BR>
18 *
19 * ```javascript
20 * api.on('connected', (): void => {
21 * console.log('API has been connected to the endpoint');
22 * });
23 *
24 * api.on('disconnected', (): void => {
25 * console.log('API has been disconnected from the endpoint');
26 * });
27 * ```
28 */
29
30
31 on(type, handler) {
32 this.#eventemitter.on(type, handler);
33 return this;
34 }
35 /**
36 * @description Remove the given eventemitter handler
37 *
38 * @param type The type of event the callback was attached to. Available events are `connected`, `disconnected`, `ready` and `error`
39 * @param handler The callback to unregister.
40 *
41 * @example
42 * <BR>
43 *
44 * ```javascript
45 * const handler = (): void => {
46 * console.log('Connected !);
47 * };
48 *
49 * // Start listening
50 * api.on('connected', handler);
51 *
52 * // Stop listening
53 * api.off('connected', handler);
54 * ```
55 */
56
57
58 off(type, handler) {
59 this.#eventemitter.removeListener(type, handler);
60 return this;
61 }
62 /**
63 * @description Attach an one-time eventemitter handler to listen to a specific event
64 *
65 * @param type The type of event to listen to. Available events are `connected`, `disconnected`, `ready` and `error`
66 * @param handler The callback to be called when the event fires. Depending on the event type, it could fire with additional arguments.
67 *
68 * @example
69 * <BR>
70 *
71 * ```javascript
72 * api.once('connected', (): void => {
73 * console.log('API has been connected to the endpoint');
74 * });
75 *
76 * api.once('disconnected', (): void => {
77 * console.log('API has been disconnected from the endpoint');
78 * });
79 * ```
80 */
81
82
83 once(type, handler) {
84 this.#eventemitter.once(type, handler);
85 return this;
86 }
87
88}
\No newline at end of file