Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
// "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
Something went wrong with that request. Please try again.