var events = require('events');
var requests = new events.EventEmitter();
function setListenerCallback(callback) {
requests.on('randomEvent', callback(message));
}
setListenerCallback(function (e) {
console.log(e);
});
Result: callback is undefined.
As you can see I am trying to set the listeners callback function from a functions argument. The result is that the function is type 'undefined' and therefore outside of the listeners scope.
So how can I use a function to set a listeners callback?
How can I access the parent functions scope from the listener?
There was a bug in the code:
Old code:
var events = require('events');
var requests = new events.EventEmitter();
function setListenerCallback(callback) {
requests.on('randomEvent', callback(message));
}
setListenerCallback(function (e) {
console.log(e);
});
New code:
var events = require('events');
var requests = new events.EventEmitter();
function setListenerCallback(callback) {
requests.on('randomEvent', callback);
}
setListenerCallback(function (e) {
console.log(e);
});
Now when the event is fired callback is called.