]>
Commit | Line | Data |
---|---|---|
2f416371 DI |
1 | /** |
2 | * @license MIT | |
3 | */ | |
4 | ||
5 | interface ListenerType { | |
6 | (): void; | |
7 | listener?: () => void; | |
8 | }; | |
9 | ||
10 | export class EventEmitter { | |
11 | private _events: {[type: string]: ListenerType[]}; | |
12 | ||
13 | constructor() { | |
937cf43e | 14 | this._events = {}; |
2f416371 DI |
15 | } |
16 | ||
17 | // TODO: Merge addListener and on, no reason for an alias in a private component | |
18 | public addListener(type, listener): void { | |
19 | this._events[type] = this._events[type] || []; | |
20 | this._events[type].push(listener); | |
21 | } | |
22 | ||
23 | public on(type, listener): void { | |
24 | this.addListener(type, listener); | |
25 | } | |
26 | ||
27 | // TODO: Merge removeListener and off, no reason for an alias in a private component | |
28 | public removeListener(type, listener): void { | |
29 | if (!this._events[type]) { | |
30 | return; | |
31 | } | |
32 | ||
33 | let obj = this._events[type]; | |
34 | let i = obj.length; | |
35 | ||
36 | while (i--) { | |
37 | if (obj[i] === listener || obj[i].listener === listener) { | |
38 | obj.splice(i, 1); | |
39 | return; | |
40 | } | |
41 | } | |
42 | } | |
43 | ||
44 | public off(type, listener): void { | |
45 | this.removeListener(type, listener); | |
46 | } | |
47 | ||
48 | public removeAllListeners(type): void { | |
49 | if (this._events[type]) { | |
50 | delete this._events[type]; | |
51 | } | |
52 | } | |
53 | ||
54 | public once(type, listener): any { | |
55 | function on() { | |
56 | let args = Array.prototype.slice.call(arguments); | |
57 | this.removeListener(type, on); | |
58 | return listener.apply(this, args); | |
59 | } | |
60 | (<any>on).listener = listener; | |
61 | return this.on(type, on); | |
62 | } | |
63 | ||
64 | public emit(type): void { | |
65 | if (!this._events[type]) { | |
66 | return; | |
67 | } | |
68 | ||
69 | let args = Array.prototype.slice.call(arguments, 1); | |
70 | let obj = this._events[type]; | |
71 | ||
72 | for (let i = 0; i < obj.length; i++) { | |
73 | obj[i].apply(this, args); | |
74 | } | |
75 | } | |
76 | ||
77 | public listeners(type): ListenerType[] { | |
78 | return this._events[type] || []; | |
79 | } | |
80 | } |