events.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict'
  2. const EventEmitter = require('events').EventEmitter
  3. const helper = require('./helper')
  4. function bufferEvents (emitter, eventsToBuffer) {
  5. const listeners = []
  6. const eventsToReply = []
  7. function genericListener () {
  8. eventsToReply.push(Array.from(arguments))
  9. }
  10. eventsToBuffer.forEach((eventName) => {
  11. const listener = genericListener.bind(null, eventName)
  12. listeners.push(listener)
  13. emitter.on(eventName, listener)
  14. })
  15. return function () {
  16. listeners.forEach((listener, i) => {
  17. emitter.removeListener(eventsToBuffer[i], listener)
  18. })
  19. eventsToReply.forEach((args) => {
  20. EventEmitter.prototype.emit.apply(emitter, args)
  21. })
  22. listeners.length = 0
  23. eventsToReply.length = 0
  24. }
  25. }
  26. class KarmaEventEmitter extends EventEmitter {
  27. bind (object) {
  28. Object.keys(object).forEach((method) => {
  29. if (method.startsWith('on') && helper.isFunction(object[method])) {
  30. this.on(helper.camelToSnake(method.substr(2)), function () {
  31. object[method].apply(object, Array.from(arguments).concat(this))
  32. })
  33. }
  34. })
  35. }
  36. emitAsync (name) {
  37. // TODO(vojta): allow passing args
  38. // TODO(vojta): ignore/throw if listener call done() multiple times
  39. let pending = this.listeners(name).length
  40. const deferred = helper.defer()
  41. this.emit(name, () => {
  42. if (!--pending) {
  43. deferred.resolve()
  44. }
  45. })
  46. if (!pending) {
  47. deferred.resolve()
  48. }
  49. return deferred.promise
  50. }
  51. }
  52. exports.EventEmitter = KarmaEventEmitter
  53. exports.bufferEvents = bufferEvents