Imagine you’re building a Single Page Application using Web Components only. You have several pages, have configured the routes, and need to be able to handle general events or actions.

Here’s when you start to think about potential solutions as well: Maybe it’s time to add state management to the application? Is it a good time to build a “custom” solution? What about using some design patterns in this case?

The answers to these questions will depend on the complexity of the current scenario, the experience of the developers, or on the opinions of the team. It is clear that there is no absolute answer!

In this article, we’ll go over how to communicate between components using a custom Event Bus implementation.

What is an Event Bus?

The Event Bus idea is generally associated with the  Publish-subscribe pattern:

Publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called ‘subscribers’, but instead, categorize published messages into classes without knowledge of subscribers

In other words, an Event Bus can be considered as a global way to transport messages or events to make them accessible from any place within the application.

Event Bus

Web Components Communication

When you’re working with Web Components through  LitElement, it’s usual firing events for sending messages between them. You can use either Standard or Custom events.

  • Fire a Standard Event using new Event('event')
  • Fire a Custom Event using new CustomEvent('event', {...options})

For a practical example, let’s assume we have two components at this time: The first one could be named as a parent component and the second one as the child component

#litelement #typescript

How to Implement an Event Bus in TypeScript
3.55 GEEK