-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathevent-dispatcher.ts
77 lines (58 loc) · 1.71 KB
/
event-dispatcher.ts
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
import type { Graph } from './graph.js';
import type { GraphNode } from './graph-node.js';
import type { GraphEdge } from './graph-edge.js';
export interface BaseEvent {
type: string;
[attachment: string]: unknown;
}
export interface GraphEvent extends BaseEvent {
target: Graph<GraphNode>;
}
export interface GraphNodeEvent extends BaseEvent {
target: GraphNode;
}
export interface GraphEdgeEvent extends BaseEvent {
target: GraphEdge<GraphNode, GraphNode>;
}
export type EventListener<E> = (event: E) => void;
export class EventDispatcher<T extends BaseEvent> {
private _listeners: Record<string, EventListener<T>[]> = {};
addEventListener(type: string, listener: EventListener<T>): this {
const listeners = this._listeners;
if (listeners[type] === undefined) {
listeners[type] = [] as EventListener<T>[];
}
if (listeners[type].indexOf(listener) === -1) {
listeners[type].push(listener);
}
return this;
}
removeEventListener(type: string, listener: EventListener<T>): this {
const listeners = this._listeners;
const listenerArray = listeners[type];
if (listenerArray !== undefined) {
const index = listenerArray.indexOf(listener);
if (index !== -1) {
listenerArray.splice(index, 1);
}
}
return this;
}
dispatchEvent(event: T): this {
const listeners = this._listeners;
const listenerArray = listeners[event.type];
if (listenerArray !== undefined) {
// Make a copy, in case listeners are removed while iterating.
const array = listenerArray.slice(0);
for (let i = 0, l = array.length; i < l; i++) {
array[i].call(this, event as T);
}
}
return this;
}
dispose(): void {
for (const key in this._listeners) {
delete this._listeners[key];
}
}
}