UNPKG

@dark-engine/platform-server

Version:
59 lines (58 loc) 2.08 kB
import { detectIsFunction, $$scope, detectIsArray } from '@dark-engine/core'; import { PREVENT } from '../constants'; class SyntheticEvent { type = ''; sourceEvent = null; target = null; propagation = true; constructor(options) { this.type = options.sourceEvent.type; this.sourceEvent = options.sourceEvent; this.target = options.target; } stopPropagation() { this.propagation = false; this.sourceEvent.stopPropagation(); } preventDefault() { this.sourceEvent.preventDefault(); } getPropagation() { return this.propagation; } } function delegateEvent(target, eventName, handler) { const $scope = $$scope(); const eventsMap = $scope.getEvents(); const handlersMap = eventsMap.get(eventName); const $handler = detectIsArray(handler) ? e => handler[0](...handler.slice(1), e) : handler; if (!handlersMap) { const rootHandler = event => { const handler = eventsMap.get(eventName).get(event.target); const target = event.target; let $event = null; target[PREVENT] && event.preventDefault(); if (detectIsFunction(handler)) { $event = new SyntheticEvent({ sourceEvent: event, target }); $scope.setIsEvent(true, $event.type === 'input'); handler($event); $scope.setIsEvent(false); } if (target.parentElement) { const shouldPropagate = $event ? $event.getPropagation() : true; if (shouldPropagate) { target.parentElement.dispatchEvent(new event.constructor(event.type, event)); } } }; eventsMap.set(eventName, new WeakMap([[target, $handler]])); document.addEventListener(eventName, rootHandler, true); $scope.addOff(() => document.removeEventListener(eventName, rootHandler, true)); } else { handlersMap.set(target, $handler); } } const detectIsEvent = attrName => attrName.startsWith('on'); const getEventName = attrName => attrName.slice(2, attrName.length).toLowerCase(); export { SyntheticEvent, delegateEvent, detectIsEvent, getEventName }; //# sourceMappingURL=events.js.map