Skip to content

Commit

Permalink
Refactor trustedDispatchEvent and rename variables
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamWr committed Apr 12, 2024
1 parent 88a5dd8 commit f174452
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions src/scriptlets/trusted-dispatch-event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,43 +51,43 @@ export function trustedDispatchEvent(
return;
}

let eventDispatched = false;
let hasBeenDispatched = false;

const listOfEvents = new Set<string>();
let eventTarget: typeof window | Document | Element | null = document;
if (target === 'window') {
eventTarget = window;
}

const events = new Set<string>();

const dispatch = () => {
const customEvent = new Event(event);

let elToDispatch;
if (target === 'window') {
elToDispatch = window;
} else if (target) {
elToDispatch = document.querySelector(target);
} else {
elToDispatch = document;
if (typeof target === 'string' && target !== 'window') {
eventTarget = document.querySelector(target);
}

const isEventAdded = listOfEvents.has(event);
if (!eventDispatched && isEventAdded && elToDispatch) {
eventDispatched = true;
const isEventAdded = events.has(event);
if (!hasBeenDispatched && isEventAdded && eventTarget) {
hasBeenDispatched = true;
hit(source);
elToDispatch.dispatchEvent(customEvent);
eventTarget.dispatchEvent(customEvent);
}
};

const wrapper = (
eventTarget: typeof EventTarget.prototype.addEventListener,
eventListener: typeof EventTarget.prototype.addEventListener,
thisArg: Element,
args: string[],
) => {
const eventName = args[0];
if (thisArg && eventName) {
listOfEvents.add(eventName);
events.add(eventName);
setTimeout(() => {
dispatch();
}, 1);
}
return Reflect.apply(eventTarget, thisArg, args);
return Reflect.apply(eventListener, thisArg, args);
};

const handler = {
Expand Down

0 comments on commit f174452

Please sign in to comment.