respondable-event
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

respondable-event

Enables event listeners to send response back to the event dispatcher.

Background

Inspired by the FetchEvent which is available to Service Workers only, the RespondableEvent allows event listeners to send a response back to the dispatching EventTarget.

This is useful in scenarios where custom elements need to communicate with the host asynchronously or infrequently. For persisted messaging, use RespondableEvent to set up Channel Messaging instead.

How to use

The code snippet below sends an "authenticate" event to the hosting page.

const event = new RespondableEvent(
  'authenticate',
  token => {
    if (token) {
      // Responded.
    } else {
      // No response.
    }
  },
  { bubbles: true } // Available to the whole page.
);

element.dispatchEvent(event);

// If `respondWith()` is not called, `checkResponse()`
// function will callback with `undefined`.
event.checkResponse();

const token = await authenticate.promise;

In the hosting page, the following code snippet responds with a token.

window.addEventListener('authenticate', event => {
  if (event.target === myTrustedElement && event.request === myTrustedRequest) {
    event.respondWith('Hello, World!');
    event.stopPropagation();
  }
});

The callback function passed to the constructor will be called at most once. Same as FetchEvent, the respondWith() function will throw if it is being called for more than once.

New checkResponse function

To reduce code complexity, the checkResponse() function guarantees the callback function will be called exactly once. The API design is similar to the HTMLFormElement.checkValidity() function:

  • If respondWith() was called, checkResponse() will return true.
  • If respondWith() was never called, checkResponse() will call the callback function with undefined, and return false.

It is recommended to put checkResponse() immediately after dispatchEvent().

Designs

Callback function in constructor

The callback function follows the pattern found in MutationObserver and other observers. It is designed to limit the number of audience who can look at the response.

Behaviors

Differences between RespondableEvent and FetchEvent

Contributions

Like us? Star us.

Want to make it better? File us an issue.

Don't like something you see? Submit a pull request.

Package Sidebar

Install

npm i respondable-event

Weekly Downloads

5

Version

0.1.0

License

MIT

Unpacked Size

18.9 kB

Total Files

9

Last publish

Collaborators

  • compulim