Reputation: 69
I couldn't get around wrapping .on
method of eventEmitter2 library to pass on my custom variable.
Try #1
let qHandler = new EventEmitter2({ wildcard: true });
const qHandlerWrapper = (queueName)=>{
qHandler.on = (eventName,callbackFunc)=>{
return qHandler.on(`${queueName}.${eventName}`,callbackFunc)
}
return qHandler
}
Here the code goes into infinite recursive call.
Try #2 - Clone the qHandler
Object
let qHandler = new EventEmitter2({ wildcard: true });
const qHandlerOnMain = require('lodash/clonedeep')(qHandler)
const qHandlerWrapper = (queueName)=>{
qHandler.on = (eventName,callbackFunc)=>{
return qHandlerOnMain.on(`${queueName}.${eventName}`,callbackFunc)
}
return qHandler
}
onAny
.Reason: I've registered all events under
qHandlerOnMain
object and returning the other -qHandler
, which leadsqHandler.onAny
to not find any events registered underqHandler
.
Upvotes: 0
Views: 107
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
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