Skip to content

Instantly share code, notes, and snippets.

@kafkadev
Forked from fabriceleal/EventEmitter.once.js
Created November 29, 2023 22:51
Show Gist options
  • Select an option

  • Save kafkadev/e1826d9392f3bbc5908d7b29c095d501 to your computer and use it in GitHub Desktop.

Select an option

Save kafkadev/e1826d9392f3bbc5908d7b29c095d501 to your computer and use it in GitHub Desktop.
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.removeListener(e, cb);
});
handler.apply(null, 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()
});
game.emit('player:disconnect', 1, 2, 3);
game.emit('player:quit', 1, 2, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment