Skip to content

Instantly share code, notes, and snippets.

@vincentmac
Created October 11, 2012 23:12
Show Gist options
  • Save vincentmac/3876225 to your computer and use it in GitHub Desktop.
Save vincentmac/3876225 to your computer and use it in GitHub Desktop.
Node.js problem getting event emitters to use named functions with arguments
/**
* The way I can currently get event emitters working.
* Look at the `.on` handler.
*
* Why do I have to wrap the listener function `executeSomeWork` in an
* anonymous function when I want to pass an argument from the emitter?
*/
function executeSomeWork(stuff) {
console.log(stuff);
}
event.emit('doSomeWork', 'print this to the console');
event.on('doSomeWork', function(stuff) {
executeSomeWork(stuff);
});
/**
* The way I want to handle event emitters.
*
* When the `listener` tries to run the `executeSomeWork` function on `line 33`, I get an
* error saying that `stuff` is not defined.
*/
function executeSomeWork(stuff) {
console.log(stuff);
}
event.emit('doSomeWork', 'print this to the console');
event.on('doSomeWork', executeSomeWork(stuff));
/**
* The way I can currently get event emitters working.
* Look at the `.on` handler.
*
* Why do I have to wrap the listener function `executeSomeWork` in an
* anonymous function when I want to pass an argument from the emitter?
*/
function executeSomeWork(stuff) {
console.log(stuff);
}
event.emit('doSomeWork', 'print this to the console');
event.on('doSomeWork', function(stuff) {
executeSomeWork(stuff);
});
/**
* The way I want to handle event emitters.
*
* When the `listener` tries to run the `executeSomeWork` function on `line 33`, I get an
* error will say that `stuff` is not defined.
*/
function executeSomeWork(stuff) {
console.log(stuff);
}
event.emit('doSomeWork', 'print this to the console');
event.on('doSomeWork', executeSomeWork(stuff));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment