In the following code, I'm trying to get mydata
passed to the callback. This is a sample problem from a bigger problem I'm having. I'm assuming this is a scope issue. What is wrong with my code and/or what should I do?
var EventEmitter = require('events').EventEmitter;
var myevent = new EventEmitter();
var mydata = 'my data!';
function myfunc (data, mydata) {
console.log(data);
console.log(mydata);
};
myevent.on('data', function(data, mydata) {myfunc(data,mydata)});
myevent.emit('data', "data!");
returns:
data!
undefined
I'd like it to return:
data!
my data!
The parameter mydata
in the callback's parameter list is hiding the global variable of the same name.
As you passed no parameter in that position, its value is undefined
.
Either:
myevent.emit('data', "data!", mydata);
p.s:
myevent.on('data', function(data, mydata) {myfunc(data,mydata)});
would be better just written as:
myevent.on('data', myfunc);
i'm going to make a wild guess (since i am not familiar with EventEmitter
) and say that emit
's first parameter is the name of the event, and the remaining parameters are passed to the handler.
if that is the case, you're not passing anything to the second callback parameter, which is why it comes in as undefined
. try this instead:
myevent.emit('data', "data!", "mydata!");
note: i am ignoring your shadowing issue as it is not related to the problem, just a bad practice.
Modified code: You can access a global variable. from anywhere you do not need to pass it as parameter. even you pass a parameter. you can access a global variable using window.mydata
since you are using nodejs you can access a global variable using global.mydata
var EventEmitter = require('events').EventEmitter;
var myevent = new EventEmitter();
var mydata = 'my data!';
function myfunc (data) {
console.log(data);
console.log(mydata);
};
myevent.on('data', myfunc);
myevent.emit('data', "data!");