michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: "use strict"; michael@0: michael@0: const { Trait } = require("../light-traits"); michael@0: const { removeListener, on } = require("../../dom/events"); michael@0: michael@0: /** michael@0: * Trait may be used for building objects / composing traits that wish to handle michael@0: * multiple dom events from multiple event targets in one place. Event targets michael@0: * can be added / removed by calling `observe / ignore` methods. Composer should michael@0: * provide array of event types it wishes to handle as property michael@0: * `supportedEventsTypes` and function for handling all those events as michael@0: * `handleEvent` property. michael@0: */ michael@0: exports.DOMEventAssembler = Trait({ michael@0: /** michael@0: * Function that is supposed to handle all the supported events (that are michael@0: * present in the `supportedEventsTypes`) from all the observed michael@0: * `eventTargets`. michael@0: * @param {Event} event michael@0: * Event being dispatched. michael@0: */ michael@0: handleEvent: Trait.required, michael@0: /** michael@0: * Array of supported event names. michael@0: * @type {String[]} michael@0: */ michael@0: supportedEventsTypes: Trait.required, michael@0: /** michael@0: * Adds `eventTarget` to the list of observed `eventTarget`s. Listeners for michael@0: * supported events will be registered on the given `eventTarget`. michael@0: * @param {EventTarget} eventTarget michael@0: */ michael@0: observe: function observe(eventTarget) { michael@0: this.supportedEventsTypes.forEach(function(eventType) { michael@0: on(eventTarget, eventType, this); michael@0: }, this); michael@0: }, michael@0: /** michael@0: * Removes `eventTarget` from the list of observed `eventTarget`s. Listeners michael@0: * for all supported events will be unregistered from the given `eventTarget`. michael@0: * @param {EventTarget} eventTarget michael@0: */ michael@0: ignore: function ignore(eventTarget) { michael@0: this.supportedEventsTypes.forEach(function(eventType) { michael@0: removeListener(eventTarget, eventType, this); michael@0: }, this); michael@0: } michael@0: });