observer.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { Trait } = require("../deprecated/light-traits");
  9. const { EventEmitterTrait: EventEmitter } = require("../deprecated/events");
  10. const { DOMEventAssembler } = require("../deprecated/events/assembler");
  11. const { browserWindowIterator } = require('../deprecated/window-utils');
  12. const { isBrowser } = require('../window/utils');
  13. const { observer: windowObserver } = require("../windows/observer");
  14. // Event emitter objects used to register listeners and emit events on them
  15. // when they occur.
  16. const observer = Trait.compose(DOMEventAssembler, EventEmitter).create({
  17. /**
  18. * Method is implemented by `EventEmitter` and is used just for emitting
  19. * events on registered listeners.
  20. */
  21. _emit: Trait.required,
  22. /**
  23. * Events that are supported and emitted by the module.
  24. */
  25. supportedEventsTypes: [ "keydown", "keyup", "keypress" ],
  26. /**
  27. * Function handles all the supported events on all the windows that are
  28. * observed. Method is used to proxy events to the listeners registered on
  29. * this event emitter.
  30. * @param {Event} event
  31. * Keyboard event being emitted.
  32. */
  33. handleEvent: function handleEvent(event) {
  34. this._emit(event.type, event, event.target.ownerDocument.defaultView);
  35. }
  36. });
  37. // Adding each opened window to a list of observed windows.
  38. windowObserver.on("open", function onOpen(window) {
  39. if (isBrowser(window))
  40. observer.observe(window);
  41. });
  42. // Removing each closed window form the list of observed windows.
  43. windowObserver.on("close", function onClose(window) {
  44. if (isBrowser(window))
  45. observer.ignore(window);
  46. });
  47. // Making observer aware of already opened windows.
  48. for each (let window in browserWindowIterator())
  49. observer.observe(window);
  50. exports.observer = observer;