baja-lite 1.5.23 → 1.5.24

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.
Files changed (3) hide show
  1. package/event.d.ts +10 -0
  2. package/event.js +38 -0
  3. package/package.json +1 -1
package/event.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ type EventParams = readonly unknown[];
2
+ type EventHandler<T extends EventParams> = (...args: T) => void;
3
+ export declare class EventBus<T extends Record<string, EventParams>> {
4
+ private readonly all;
5
+ on<K extends keyof T>(type: K, handler: EventHandler<T[K]>): this;
6
+ once<K extends keyof T>(type: K, handler: EventHandler<T[K]>): this;
7
+ off<K extends keyof T>(type: K, handler?: EventHandler<T[K]>): this;
8
+ emit<K extends keyof T>(type: K, ...args: T[K]): this;
9
+ }
10
+ export {};
package/event.js ADDED
@@ -0,0 +1,38 @@
1
+ export class EventBus {
2
+ constructor() {
3
+ this.all = new Map();
4
+ }
5
+ on(type, handler) {
6
+ let list = this.all.get(type);
7
+ if (!list)
8
+ this.all.set(type, (list = []));
9
+ list.push(handler);
10
+ return this;
11
+ }
12
+ once(type, handler) {
13
+ const wrapper = (...args) => {
14
+ handler(...args);
15
+ this.off(type, wrapper);
16
+ };
17
+ return this.on(type, wrapper);
18
+ }
19
+ off(type, handler) {
20
+ const list = this.all.get(type);
21
+ if (!list)
22
+ return this;
23
+ if (handler) {
24
+ const idx = list.indexOf(handler);
25
+ if (idx !== -1)
26
+ list.splice(idx, 1);
27
+ }
28
+ else {
29
+ this.all.delete(type);
30
+ }
31
+ return this;
32
+ }
33
+ emit(type, ...args) {
34
+ const list = this.all.get(type);
35
+ list?.slice().forEach(fn => fn(...args));
36
+ return this;
37
+ }
38
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baja-lite",
3
- "version": "1.5.23",
3
+ "version": "1.5.24",
4
4
  "description": "some util for self",
5
5
  "homepage": "https://github.com/void-soul/baja-lite",
6
6
  "repository": {