locomotivemtl / locomotive-boilerplate

🚂 Front-end boilerplate for projects by Locomotive.
https://locomotivemtl-boilerplate.vercel.app/
MIT License
458 stars 71 forks source link

Refactor visibility.js #99

Closed mcaskill closed 2 years ago

mcaskill commented 2 years ago

Replaced the visibilityApi interface and custom callback stacks with a simple feature toggler that uses custom event types and the native event listener interface.

The new PageVisibility interface provides support for dispatching a custom event derived from the value of document.visibilityState when the visibilitychange event is fired.

The custom events are:

Example:

import pageVisibility from './utils/visibility.js';

pageVisibility.enableCustomEvents();

document.addEventListener('visibilityhidden', () => videoElement.pause());

The visibilitychange event is accessible from the detail property on the custom event:

document.addEventListener('visibilityhidden', ({ detail: cause: originalEvent }) => {
    console.log(originalEvent);
});

The PageVisibility interface does not manage the attachment/detachment of event listeners on the custom event types.

mcaskill commented 2 years ago

Thanks. I've fixed the broken usage of EventTarget#dispatchEvent.

I think this feature should, eventually, be moved to the cookbook.