target.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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": "stable"
  7. };
  8. const { on, once, off, setListeners } = require('./core');
  9. const { method, chainable } = require('../lang/functional');
  10. const { Class } = require('../core/heritage');
  11. /**
  12. * `EventTarget` is an exemplar for creating an objects that can be used to
  13. * add / remove event listeners on them. Events on these objects may be emitted
  14. * via `emit` function exported by 'event/core' module.
  15. */
  16. const EventTarget = Class({
  17. /**
  18. * Method initializes `this` event source. It goes through properties of a
  19. * given `options` and registers listeners for the ones that look like an
  20. * event listeners.
  21. */
  22. /**
  23. * Method initializes `this` event source. It goes through properties of a
  24. * given `options` and registers listeners for the ones that look like an
  25. * event listeners.
  26. */
  27. initialize: function initialize(options) {
  28. setListeners(this, options);
  29. },
  30. /**
  31. * Registers an event `listener` that is called every time events of
  32. * specified `type` are emitted.
  33. * @param {String} type
  34. * The type of event.
  35. * @param {Function} listener
  36. * The listener function that processes the event.
  37. * @example
  38. * worker.on('message', function (data) {
  39. * console.log('data received: ' + data)
  40. * })
  41. */
  42. on: chainable(method(on)),
  43. /**
  44. * Registers an event `listener` that is called once the next time an event
  45. * of the specified `type` is emitted.
  46. * @param {String} type
  47. * The type of the event.
  48. * @param {Function} listener
  49. * The listener function that processes the event.
  50. */
  51. once: chainable(method(once)),
  52. /**
  53. * Removes an event `listener` for the given event `type`.
  54. * @param {String} type
  55. * The type of event.
  56. * @param {Function} listener
  57. * The listener function that processes the event.
  58. */
  59. removeListener: function removeListener(type, listener) {
  60. // Note: We can't just wrap `off` in `method` as we do it for other methods
  61. // cause skipping a second or third argument will behave very differently
  62. // than intended. This way we make sure all arguments are passed and only
  63. // one listener is removed at most.
  64. off(this, type, listener);
  65. return this;
  66. },
  67. off: function(type, listener) {
  68. off(this, type, listener);
  69. return this;
  70. }
  71. });
  72. exports.EventTarget = EventTarget;