Reputation: 796
I'm attempting to write an extension of a Node library. The library exports a class that extends EventEmitter (class LibClass extends EventEmitter
). It is responsible for establishing a websocket connection, and instances of the class fire a "ready" event (with no arguments) when the connection is established.
I would like to subclass this existing class (class MyClass extends LibClass
), and when that "ready" event is emitted from the superclass, I want to hold it until my class performs additional setup, then re-emit it afterwards. Functionally, I want all the methods of LibClass
to be on MyClass
, but I want to override the behavior of certain events like this.
How would I go about doing something like this? Can it be done via sub-classing, or do I have to hold a reference to a LibClass
instance somewhere and repeat all the relevant methods and events in my own class to redirect them to that instance?
Upvotes: 2
Views: 440
Reputation: 73
Even if it works by using a subclass and this scary override of emit
, it really does not mean you should do it this way. EventEmitters were not designed to be overridden, so the resulting code would be hard to follow, and easy to break with future changes.
Composition was the clean, safe, and maintainable way to go, as you suggested in your question ("hold a reference to a LibClass instance somewhere and repeat all the relevant methods and events in my own class to redirect them to that instance").
Upvotes: 0
Reputation: 796
As Bergi said in the comments, the solution was to override the emit
event like so:
class MyClass extends LibClass {
constructor() {
super();
// ...
}
emit(name, ...args) {
if (name === 'someEvent') {
// Do custom setup for this event
}
// Other events will pass through unmodified
// When setup is completed, or if the event shouldn't be intercepted:
super.emit(name, ...args);
}
}
Upvotes: 1