Christoph Pohl Christoph Pohl - 4 months ago 8
Node.js Question

Allow only certain events

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:

const EventEmitter = require('events');

class myEvent extends EventEmitter {
constructor() {
super();
var self = this;
setInterval(function() {
self.emit('1stEvent');
}, 1000)
setInterval(function() {
self.emit('2ndEvent');
}, 2000)
}

}

var MyEvent = new myEvent();
MyEvent.on('1stEvent', function () {
console.log('1st Event triggered');
});
MyEvent.on('2ndEvent', function () {
console.log('2nd Event triggered');
});
MyEvent.on('3rdEvent', function () {
console.log('3rd Event triggered');
});


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?

Answer

Tere are no built-in functionality, but you can create some kind of wrapper to do this.

const EventEmitter = require('events');

class myEvent extends EventEmitter {
    constructor() {
        super();

        this._events = new Set();
        this._events.add('1stEvent');      
        this._events.add('2ndEvent');   

        var self = this;
        setInterval(function() {
            self.emit('1stEvent');
        }, 1000)
        setInterval(function() {
            self.emit('2ndEvent');
        }, 2000)
    }

    on(event, callback) {
      if(!this.events.has(event)) {
        console.log('Event not registered'); 
        return;
      }

      super.on(event, callback);
    }

}