Is there a way to only allow certain events in a custom eventEmitter
?
For example, if I have something like this everything works as expected:
JavaScript
x
27
27
1
const EventEmitter = require('events');
2
3
class myEvent extends EventEmitter {
4
constructor() {
5
super();
6
var self = this;
7
setInterval(function() {
8
self.emit('1stEvent');
9
}, 1000)
10
setInterval(function() {
11
self.emit('2ndEvent');
12
}, 2000)
13
}
14
15
}
16
17
var MyEvent = new myEvent();
18
MyEvent.on('1stEvent', function () {
19
console.log('1st Event triggered');
20
});
21
MyEvent.on('2ndEvent', function () {
22
console.log('2nd Event triggered');
23
});
24
MyEvent.on('3rdEvent', function () {
25
console.log('3rd Event triggered');
26
});
27
I get a callback every second on the first event and every 2 seconds on the 2nd event. For the 3rd nothing happens, because I don’t emit this event. Is there a way that this class tells me that this event is not defined and I cannot add a listener to it, or that it is only possible to add listeners to event 1 and 2?
Advertisement
Answer
There is no built-in functionality, but you can create some kind of wrapper to do this.
JavaScript
1
30
30
1
const EventEmitter = require('events');
2
3
class myEvent extends EventEmitter {
4
constructor() {
5
super();
6
7
this._events = new Set();
8
this._events.add('1stEvent');
9
this._events.add('2ndEvent');
10
11
var self = this;
12
setInterval(function() {
13
self.emit('1stEvent');
14
}, 1000)
15
setInterval(function() {
16
self.emit('2ndEvent');
17
}, 2000)
18
}
19
20
on(event, callback) {
21
if(!this._events.has(event)) {
22
console.log('Event not registered');
23
return;
24
}
25
26
super.on(event, callback);
27
}
28
29
}
30