Search code examples
javascriptnode.jseventemitter

node: When subclassing an existing subclass of EventEmitter, how can I intercept events from the superclass?


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?


Solution

  • 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);
      }
    }