assembler.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. const { Trait } = require("../light-traits");
  6. const { removeListener, on } = require("../../dom/events");
  7. /**
  8. * Trait may be used for building objects / composing traits that wish to handle
  9. * multiple dom events from multiple event targets in one place. Event targets
  10. * can be added / removed by calling `observe / ignore` methods. Composer should
  11. * provide array of event types it wishes to handle as property
  12. * `supportedEventsTypes` and function for handling all those events as
  13. * `handleEvent` property.
  14. */
  15. exports.DOMEventAssembler = Trait({
  16. /**
  17. * Function that is supposed to handle all the supported events (that are
  18. * present in the `supportedEventsTypes`) from all the observed
  19. * `eventTargets`.
  20. * @param {Event} event
  21. * Event being dispatched.
  22. */
  23. handleEvent: Trait.required,
  24. /**
  25. * Array of supported event names.
  26. * @type {String[]}
  27. */
  28. supportedEventsTypes: Trait.required,
  29. /**
  30. * Adds `eventTarget` to the list of observed `eventTarget`s. Listeners for
  31. * supported events will be registered on the given `eventTarget`.
  32. * @param {EventTarget} eventTarget
  33. */
  34. observe: function observe(eventTarget) {
  35. this.supportedEventsTypes.forEach(function(eventType) {
  36. on(eventTarget, eventType, this);
  37. }, this);
  38. },
  39. /**
  40. * Removes `eventTarget` from the list of observed `eventTarget`s. Listeners
  41. * for all supported events will be unregistered from the given `eventTarget`.
  42. * @param {EventTarget} eventTarget
  43. */
  44. ignore: function ignore(eventTarget) {
  45. this.supportedEventsTypes.forEach(function(eventType) {
  46. removeListener(eventTarget, eventType, this);
  47. }, this);
  48. }
  49. });