-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathEventEmitter.js
More file actions
48 lines (38 loc) · 1.1 KB
/
EventEmitter.js
File metadata and controls
48 lines (38 loc) · 1.1 KB
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
// Implement an Event Emitter class similar to the one in NodeJS.
// It should have an on, off and emit method.
// When the event is emitted, any function that has subscribed to an event should fire.
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if(this.events[event]) {
this.events[event].push(listener)
}
else this.events[event] = [listener];
}
off(event, listener) {
const listeners = this.events[event];
if(listeners) {
this.events[event] = listeners.filter(
(l) => l !== listener
);
}
}
emit(event, ...args) {
const listeners = this.events[event];
if(listeners) {
listeners.forEach( listener => listener(...args));
}
}
}
/* ======== Usage ======== */
const emitter = new EventEmitter();
const onScroll = () => console.log("scrolling");
const onType = () => console.log("typing");
emitter.on('scroll', onScroll);
emitter.on('type', onType);
emitter.emit('scroll') // scrolling
emitter.off('scroll', onScroll);
emitter.emit('scroll'); //nothing happens
emitter.emit('type', onType); //typing