Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.6KB

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