]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/EventEmitter.ts
Merge pull request #926 from ficristo/search-fix
[mirror_xterm.js.git] / src / EventEmitter.ts
1 /**
2 * @license MIT
3 */
4
5 import { IEventEmitter } from './Interfaces';
6
7 interface ListenerType {
8 (): void;
9 listener?: () => void;
10 };
11
12 export class EventEmitter implements IEventEmitter {
13 private _events: {[type: string]: ListenerType[]};
14
15 constructor() {
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 || {};
19 }
20
21 public on(type, listener): void {
22 this._events[type] = this._events[type] || [];
23 this._events[type].push(listener);
24 }
25
26 public off(type, listener): void {
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
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);
51 this.off(type, on);
52 return listener.apply(this, args);
53 }
54 (<any>on).listener = listener;
55 return this.on(type, on);
56 }
57
58 public emit(type: string, ...args: any[]): void {
59 if (!this._events[type]) {
60 return;
61 }
62 let obj = this._events[type];
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 }