]>
Commit | Line | Data |
---|---|---|
2f416371 DI |
1 | /** |
2 | * @license MIT | |
3 | */ | |
4 | ||
59f75555 DI |
5 | import { IEventEmitter } from './Interfaces'; |
6 | ||
2f416371 DI |
7 | interface ListenerType { |
8 | (): void; | |
9 | listener?: () => void; | |
10 | }; | |
11 | ||
59f75555 | 12 | export class EventEmitter implements IEventEmitter { |
2f416371 DI |
13 | private _events: {[type: string]: ListenerType[]}; |
14 | ||
15 | constructor() { | |
996c25a3 DI |
16 | // Restore the previous events if available, this will happen if the |
17 | // constructor is called multiple times on the same object (terminal reset). | |
18 | this._events = this._events || {}; | |
2f416371 DI |
19 | } |
20 | ||
0d9d3aca | 21 | public on(type, listener): void { |
2f416371 DI |
22 | this._events[type] = this._events[type] || []; |
23 | this._events[type].push(listener); | |
24 | } | |
25 | ||
0d9d3aca | 26 | public off(type, listener): void { |
2f416371 DI |
27 | if (!this._events[type]) { |
28 | return; | |
29 | } | |
30 | ||
31 | let obj = this._events[type]; | |
32 | let i = obj.length; | |
33 | ||
34 | while (i--) { | |
35 | if (obj[i] === listener || obj[i].listener === listener) { | |
36 | obj.splice(i, 1); | |
37 | return; | |
38 | } | |
39 | } | |
40 | } | |
41 | ||
2f416371 DI |
42 | public removeAllListeners(type): void { |
43 | if (this._events[type]) { | |
44 | delete this._events[type]; | |
45 | } | |
46 | } | |
47 | ||
48 | public once(type, listener): any { | |
49 | function on() { | |
50 | let args = Array.prototype.slice.call(arguments); | |
965ebde2 | 51 | this.off(type, on); |
2f416371 DI |
52 | return listener.apply(this, args); |
53 | } | |
54 | (<any>on).listener = listener; | |
55 | return this.on(type, on); | |
56 | } | |
57 | ||
ea008411 | 58 | public emit(type: string, ...args: any[]): void { |
2f416371 DI |
59 | if (!this._events[type]) { |
60 | return; | |
61 | } | |
2f416371 | 62 | let obj = this._events[type]; |
2f416371 DI |
63 | for (let i = 0; i < obj.length; i++) { |
64 | obj[i].apply(this, args); | |
65 | } | |
66 | } | |
67 | ||
68 | public listeners(type): ListenerType[] { | |
69 | return this._events[type] || []; | |
70 | } | |
71 | } |