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.

57 lines
1.2 KiB

4 years ago
  1. 'use strict';
  2. var inherits = require('inherits')
  3. , EventTarget = require('./eventtarget')
  4. ;
  5. function EventEmitter() {
  6. EventTarget.call(this);
  7. }
  8. inherits(EventEmitter, EventTarget);
  9. EventEmitter.prototype.removeAllListeners = function(type) {
  10. if (type) {
  11. delete this._listeners[type];
  12. } else {
  13. this._listeners = {};
  14. }
  15. };
  16. EventEmitter.prototype.once = function(type, listener) {
  17. var self = this
  18. , fired = false;
  19. function g() {
  20. self.removeListener(type, g);
  21. if (!fired) {
  22. fired = true;
  23. listener.apply(this, arguments);
  24. }
  25. }
  26. this.on(type, g);
  27. };
  28. EventEmitter.prototype.emit = function() {
  29. var type = arguments[0];
  30. var listeners = this._listeners[type];
  31. if (!listeners) {
  32. return;
  33. }
  34. // equivalent of Array.prototype.slice.call(arguments, 1);
  35. var l = arguments.length;
  36. var args = new Array(l - 1);
  37. for (var ai = 1; ai < l; ai++) {
  38. args[ai - 1] = arguments[ai];
  39. }
  40. for (var i = 0; i < listeners.length; i++) {
  41. listeners[i].apply(this, args);
  42. }
  43. };
  44. EventEmitter.prototype.on = EventEmitter.prototype.addListener = EventTarget.prototype.addEventListener;
  45. EventEmitter.prototype.removeListener = EventTarget.prototype.removeEventListener;
  46. module.exports.EventEmitter = EventEmitter;