Ensure sending and receiver of custom events is the same obj

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-05-03

When sending custom events, make the dispatcher and receiver objects the same

const event = new window.Event("loadedPage");
document.dispatchEvent(event);

// This callback -- on `window` was never called
window.addEventListener("loadedPage", callback);

// However this one -- on `document` -- got called
document.addEventListener("loadedPage", callback);

// By contrast, if I did `window.dispatchEvent` then
// window.dispatchEvent would have caught it.

Make sure the event listener is set up.

If this code gets called

const event = new window.Event("loadedPage");
document.dispatchEvent(event);

Before this code has the chance to run and set itself up, then we have a bug

// This callback -- on `window` was never called
document.addEventListener("loadedPage", callback);