Created
September 4, 2012 23:08
-
-
Save fabriceleal/3627823 to your computer and use it in GitHub Desktop.
node.js EventEmitter.once (with example) (answer for http://stackoverflow.com/questions/12150540/javascript-eventemitter-multiple-events-once)
This file contains 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
// "Extend" the EventEmitter like this: | |
var EventEmitter = require('events').EventEmitter; | |
EventEmitter.prototype.once = function(events, handler){ | |
// no events, get out! | |
if(! events) | |
return; | |
// Ugly, but helps getting the rest of the function | |
// short and simple to the eye ... I guess... | |
if(!(events instanceof Array)) | |
events = [events]; | |
var _this = this; | |
var cb = function(){ | |
events.forEach(function(e){ | |
// This only removes the listener itself | |
// from all the events that are listening to it | |
// i.e., does not remove other listeners to the same event! | |
_this.removeListener(e, cb); | |
}); | |
// This will allow any args you put in xxx.emit('event', ...) to be sent | |
// to your handler | |
handler.apply(_this, Array.prototype.slice.call(arguments, 0)); | |
}; | |
events.forEach(function(e){ | |
_this.addListener(e, cb); | |
}); | |
}; | |
// EXAMPLE | |
var game = new EventEmitter(); | |
game.endGame = function(){ | |
console.log('Game ended!'); | |
}; | |
game.on('player:quit', function(){ | |
console.log('quit') | |
}); | |
game.on('player:disconnect', function(){ | |
console.log('disconnect') | |
}); | |
game.once(['player:quit', 'player:disconnect'], function (a, b, c) { | |
console.log('Disconnecting...'); | |
console.log('arg 1: ' + a); | |
console.log('arg 2: ' + b); | |
console.log('arg 3: ' + c); | |
game.endGame() | |
}); | |
// This will exec our handler... | |
game.emit('player:disconnect', 1, 2, 3); | |
// This one will exec no handler... | |
game.emit('player:quit', 4, 5, 6); | |
/* | |
This outputs: | |
Disconnecting... | |
arg 1: 1 | |
arg 2: 2 | |
arg 3: 3 | |
Game ended! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment