Created
October 11, 2012 23:12
-
-
Save vincentmac/3876225 to your computer and use it in GitHub Desktop.
Node.js problem getting event emitters to use named functions with arguments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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