source: trip-planner-front/node_modules/ee-first/index.js@ 6a3a178

Last change on this file since 6a3a178 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.6 KB
Line 
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
14module.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
24function 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
80function 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}
Note: See TracBrowser for help on using the repository browser.