Mukesh Suthar
Mukesh Suthar

Reputation: 69

How to wrap a "method" in Javascript?

I couldn't get around wrapping .on method of eventEmitter2 library to pass on my custom variable.

Upvotes: 0

Views: 107

Answers (2)

Dmitriy Mozgovoy
Dmitriy Mozgovoy

Reputation: 1597

I'm not sure what you are actually trying to do here, but using private library methods is not a good idea, since we may change its signature in the near future. Moreover, this is definitely a bad approach to fixing the EventEmitter2 prototype. This will affect all other instances. Many other modules use EventEmitter2. You should subclass EventEmitter2 to change the implementation of the on method for the own purpose. But according to your code:

const originalOn= EventEmitter2.prototype.on;

const qHandlerWrapper = (queueName)=>{        
    // this is a bad idea!!!
    EventEmitter2.prototype.on = function(type, listener, options) {
    // wildcard emitter accepts an array as event path
        return originalOn.call(this, [queueName, type], listener, options);
    };

    return qHandler;
}

I can't offer a more suitable solution as I do not understand your needs. Why are you cloning an Eventemitter instance and for what purpose are you trying to bind the queueName to the on method.

Upvotes: 1

Mukesh Suthar
Mukesh Suthar

Reputation: 69

Finally, I had to add my wrapper code on eventEmitter2 prototype

let qHandler = new EventEmitter2({ wildcard: true });
  
const qHandlerWrapper = (queueName)=>{  
    EventEmitter2.prototype.on = function(type, listener, options) {
      return this._on(`${queueName}.${type}`, listener, false, options);
    };
    return qHandler;
}

Upvotes: 0

Related Questions