Created
September 2, 2014 11:39
-
-
Save slaskis/37f96571066fa732ff2d to your computer and use it in GitHub Desktop.
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
var Emitter = require('emitter'); | |
var slice = [].slice; | |
module.exports = QueueEmitter; | |
function QueueEmitter(){ | |
if( !(this instanceof QueueEmitter) ){ | |
return new QueueEmitter(); | |
} | |
this.queued = {}; | |
} | |
Emitter(QueueEmitter.prototype); | |
var emit = QueueEmitter.prototype.emit; | |
QueueEmitter.prototype.emit = function(event){ | |
var q = this.queued[event] = (this.queued[event] || []); | |
q.push(slice.call(arguments)); | |
} | |
QueueEmitter.prototype.flush = function(event){ | |
if( this.queued[event] ){ | |
var q = this.queued[event]; | |
for(var i=0; i<q.length; i++){ | |
emit.apply(this, [event].concat(q[i])); | |
} | |
} | |
} | |
QueueEmitter.prototype.reset = function(event){ | |
if( event ){ | |
this.queued[event] = []; | |
} else { | |
this.queued = {}; | |
} | |
} | |
var a = QueueEmitter(); | |
a.on('hi', console.log.bind(console, 'hi')); | |
a.on('no', console.log.bind(console, 'no')); | |
a.on('oh', console.log.bind(console, 'oh')); | |
// nothing happens (queued) | |
a.emit('hi', 1); | |
a.emit('hi', 2); | |
a.emit('hi', 3); | |
a.emit('hi', 4); | |
a.emit('no', 1); | |
a.emit('no', 2); | |
a.emit('ok', 1); | |
a.flush('hi'); // 4 emits happens | |
a.flush('hi'); // 4 emits happen again (in case needed in multiple systems) | |
a.flush('no'); // 2 emits happens | |
a.flush('oh'); // 0 emits happens | |
a.flush('ok'); // 1 emits happens, no listeners though... | |
a.reset('no'); // part of queue is cleared | |
a.flush('hi'); // 4 emits still happens | |
a.flush('no'); // 0 emits happens. cleared. | |
a.reset(); // entire queue is cleared | |
a.flush('hi'); // 0 emits happens | |
a.flush('no'); // 0 emits happens | |
a.flush('oh'); // 0 emits happens | |
a.flush('ok'); // 0 emits happens |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment