public
Last active

  • Download Gist
EventEmitter.once.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
// "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!
*/

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.