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.

62 lines
1.8 KiB

4 years ago
  1. 'use strict';
  2. /* Simplified implementation of DOM2 EventTarget.
  3. * http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
  4. */
  5. function EventTarget() {
  6. this._listeners = {};
  7. }
  8. EventTarget.prototype.addEventListener = function(eventType, listener) {
  9. if (!(eventType in this._listeners)) {
  10. this._listeners[eventType] = [];
  11. }
  12. var arr = this._listeners[eventType];
  13. // #4
  14. if (arr.indexOf(listener) === -1) {
  15. // Make a copy so as not to interfere with a current dispatchEvent.
  16. arr = arr.concat([listener]);
  17. }
  18. this._listeners[eventType] = arr;
  19. };
  20. EventTarget.prototype.removeEventListener = function(eventType, listener) {
  21. var arr = this._listeners[eventType];
  22. if (!arr) {
  23. return;
  24. }
  25. var idx = arr.indexOf(listener);
  26. if (idx !== -1) {
  27. if (arr.length > 1) {
  28. // Make a copy so as not to interfere with a current dispatchEvent.
  29. this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));
  30. } else {
  31. delete this._listeners[eventType];
  32. }
  33. return;
  34. }
  35. };
  36. EventTarget.prototype.dispatchEvent = function() {
  37. var event = arguments[0];
  38. var t = event.type;
  39. // equivalent of Array.prototype.slice.call(arguments, 0);
  40. var args = arguments.length === 1 ? [event] : Array.apply(null, arguments);
  41. // TODO: This doesn't match the real behavior; per spec, onfoo get
  42. // their place in line from the /first/ time they're set from
  43. // non-null. Although WebKit bumps it to the end every time it's
  44. // set.
  45. if (this['on' + t]) {
  46. this['on' + t].apply(this, args);
  47. }
  48. if (t in this._listeners) {
  49. // Grab a reference to the listeners list. removeEventListener may alter the list.
  50. var listeners = this._listeners[t];
  51. for (var i = 0; i < listeners.length; i++) {
  52. listeners[i].apply(this, args);
  53. }
  54. }
  55. };
  56. module.exports = EventTarget;