summaryrefslogtreecommitdiffstats
path: root/toolkit/jetpack/sdk/deprecated/events/assembler.js
blob: bb297c24f0e6b7a22925389d346d80c6d5b81143 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

const { Class } = require("../../core/heritage");
const { removeListener, on } = require("../../dom/events");

/**
 * Event targets
 * can be added / removed by calling `observe / ignore` methods. Composer should
 * provide array of event types it wishes to handle as property
 * `supportedEventsTypes` and function for handling all those events as
 * `handleEvent` property.
 */
exports.DOMEventAssembler = Class({
  /**
   * Function that is supposed to handle all the supported events (that are
   * present in the `supportedEventsTypes`) from all the observed
   * `eventTargets`.
   * @param {Event} event
   *    Event being dispatched.
   */
  handleEvent() {
    throw new TypeError("Instance of DOMEventAssembler must implement `handleEvent` method");
  },
  /**
   * Array of supported event names.
   * @type {String[]}
   */
  get supportedEventsTypes() {
    throw new TypeError("Instance of DOMEventAssembler must implement `handleEvent` field");
  },
  /**
   * Adds `eventTarget` to the list of observed `eventTarget`s. Listeners for
   * supported events will be registered on the given `eventTarget`.
   * @param {EventTarget} eventTarget
   */
  observe: function observe(eventTarget) {
    this.supportedEventsTypes.forEach(function(eventType) {
      on(eventTarget, eventType, this);
    }, this);
  },
  /**
   * Removes `eventTarget` from the list of observed `eventTarget`s. Listeners
   * for all supported events will be unregistered from the given `eventTarget`.
   * @param {EventTarget} eventTarget
   */
  ignore: function ignore(eventTarget) {
    this.supportedEventsTypes.forEach(function(eventType) {
      removeListener(eventTarget, eventType, this);
    }, this);
  }
});