index.js (1684B)
1 /*! 2 * ee-first 3 * Copyright(c) 2014 Jonathan Ong 4 * MIT Licensed 5 */ 6 7 'use strict' 8 9 /** 10 * Module exports. 11 * @public 12 */ 13 14 module.exports = first 15 16 /** 17 * Get the first event in a set of event emitters and event pairs. 18 * 19 * @param {array} stuff 20 * @param {function} done 21 * @public 22 */ 23 24 function first(stuff, done) { 25 if (!Array.isArray(stuff)) 26 throw new TypeError('arg must be an array of [ee, events...] arrays') 27 28 var cleanups = [] 29 30 for (var i = 0; i < stuff.length; i++) { 31 var arr = stuff[i] 32 33 if (!Array.isArray(arr) || arr.length < 2) 34 throw new TypeError('each array member must be [ee, events...]') 35 36 var ee = arr[0] 37 38 for (var j = 1; j < arr.length; j++) { 39 var event = arr[j] 40 var fn = listener(event, callback) 41 42 // listen to the event 43 ee.on(event, fn) 44 // push this listener to the list of cleanups 45 cleanups.push({ 46 ee: ee, 47 event: event, 48 fn: fn, 49 }) 50 } 51 } 52 53 function callback() { 54 cleanup() 55 done.apply(null, arguments) 56 } 57 58 function cleanup() { 59 var x 60 for (var i = 0; i < cleanups.length; i++) { 61 x = cleanups[i] 62 x.ee.removeListener(x.event, x.fn) 63 } 64 } 65 66 function thunk(fn) { 67 done = fn 68 } 69 70 thunk.cancel = cleanup 71 72 return thunk 73 } 74 75 /** 76 * Create the event listener. 77 * @private 78 */ 79 80 function listener(event, done) { 81 return function onevent(arg1) { 82 var args = new Array(arguments.length) 83 var ee = this 84 var err = event === 'error' 85 ? arg1 86 : null 87 88 // copy args to prevent arguments escaping scope 89 for (var i = 0; i < args.length; i++) { 90 args[i] = arguments[i] 91 } 92 93 done(err, ee, event, args) 94 } 95 }