mvdom
Version:
deprecated - Moved to dom-native package
78 lines • 2.71 kB
JavaScript
import { off, on } from './event';
const onEventsByConstructor = new Map();
const hasOnWinEvent = new Map();
const hasOnDocEvent = new Map();
export function onEvent(type, selector) {
return _onDOMEvent(null, type, selector);
}
export function onDoc(type, selector) {
return _onDOMEvent(document, type, selector);
}
export function onWin(type, selector) {
return _onDOMEvent(window, type, selector);
}
function _onDOMEvent(evtTarget, type, selector) {
return function (target, propertyKey, descriptor) {
const fn = descriptor.value;
const clazz = target.constructor;
let onEvents = onEventsByConstructor.get(clazz);
if (onEvents == null) {
onEvents = [];
onEventsByConstructor.set(clazz, onEvents);
}
const onEvent = {
target: evtTarget,
name: propertyKey,
type: type,
selector: selector || null
};
onEvents.push(onEvent);
};
}
export function bindOnEventsDecorators() {
let clazz = this.constructor;
const topClazz = clazz;
let setHasDocEvent = !hasOnDocEvent.has(topClazz);
let setHasWinEvent = !hasOnWinEvent.has(topClazz);
const fnNameBoundSet = new Set();
const opts = { ...this._nsObj, ctx: this };
while (clazz !== HTMLElement) {
const onEvents = onEventsByConstructor.get(clazz);
if (onEvents) {
for (const onEvent of onEvents) {
const fnName = onEvent.name;
if (!fnNameBoundSet.has(fnName)) {
const fn = this[fnName];
if (setHasDocEvent && onEvent.target === document) {
hasOnDocEvent.set(topClazz, true);
setHasDocEvent = false;
}
if (setHasWinEvent && onEvent.target === window) {
hasOnWinEvent.set(topClazz, true);
setHasWinEvent = false;
}
const target = onEvent.target || this;
on(target, onEvent.type, onEvent.selector, fn, opts);
fnNameBoundSet.add(fnName);
}
}
}
clazz = Object.getPrototypeOf(clazz);
}
if (setHasDocEvent) {
hasOnDocEvent.set(topClazz, false);
}
if (setHasWinEvent) {
hasOnWinEvent.set(topClazz, false);
}
}
export function unbindOnEventsDecorators() {
const clazz = this.constructor;
if (hasOnDocEvent.get(clazz)) {
off(document, this._nsObj);
}
if (hasOnWinEvent.get(clazz)) {
off(window, this._nsObj);
}
}
//# sourceMappingURL=ts-decorator-on-event.js.map