Skip to content

compulim/respondable-event

Repository files navigation

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();

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.
    • Subsequent calls to checkResponse() will return true.

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.

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •