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.

EventEmitterForwarder.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Implements utility to forward events from one eventEmitter to another.
  3. * @param src {object} instance of EventEmitter or another class that implements
  4. * addListener method which will register listener to EventEmitter instance.
  5. * @param dest {object} instance of EventEmitter or another class that
  6. * implements emit method which will emit an event.
  7. */
  8. function EventEmitterForwarder (src, dest) {
  9. if (!src || !dest || typeof(src.addListener) !== "function" ||
  10. typeof(dest.emit) !== "function")
  11. throw new Error("Invalid arguments passed to EventEmitterForwarder");
  12. this.src = src;
  13. this.dest = dest;
  14. }
  15. /**
  16. * Adds event to be forwarded from src to dest.
  17. * @param srcEvent {string} the event that EventEmitterForwarder is listening
  18. * for.
  19. * @param dstEvent {string} the event that will be fired from dest.
  20. * @param arguments all other passed arguments are going to be fired with
  21. * dstEvent.
  22. */
  23. EventEmitterForwarder.prototype.forward = function () {
  24. // This line is only for fixing jshint errors.
  25. var args = arguments;
  26. var srcEvent = args[0];
  27. //This will be the "this" value for emit function.
  28. args[0] = this.dest;
  29. //Using bind.apply to pass the arguments as Array-like object ("arguments")
  30. this.src.addListener(srcEvent,
  31. Function.prototype.bind.apply(this.dest.emit, args));
  32. };
  33. module.exports = EventEmitterForwarder;