UNPKG

1.38 kBJavaScriptView Raw
1/**
2 * Event emitter class
3 */
4export class Emitter {
5 /**
6 * Creates an instance of Emitter.
7 */
8 constructor() {
9 /**
10 * Events object
11 * @type {Object}
12 */
13 this.events = {};
14 }
15
16 /**
17 * Subscribe to an event
18 * @param {Array} evts Collection of event names
19 * @param {Function} fn Function invoked when event is emitted
20 */
21 on(evts, fn) {
22 evts.forEach((evt) => {
23 this.events[evt] = this.events[evt] || [];
24 this.events[evt].push(fn);
25 });
26 }
27
28 /**
29 * Unsubscribe to an event
30 * @param {Array} evts Collection of event names
31 * @param {Function} fn Function invoked when event is emitted
32 */
33 off(evts, fn) {
34 evts.forEach((evt) => {
35 if (evt in this.events) {
36 this.events[evt].splice(this.events[evt].indexOf(fn), 1);
37 }
38 });
39 }
40
41 /**
42 * Emit an event
43 * @param {String} evt Event name followed by any other argument passed to
44 * the invoked function
45 */
46 emit(evt /*, args...*/) {
47 if (evt in this.events) {
48 for (let i = 0; i < this.events[evt].length; i++) {
49 this.events[evt][i].apply(this, [].slice.call(arguments, 1));
50 }
51 }
52 }
53}