Let's Create a Lightweight Native Event Bus in JavaScript
Event bus is a design pattern (although we will discuss JavaScript here, it is a design pattern in any language) that can be used to simplify communication between different components. It can also be considered a publish/subscribe or pubsub.
The idea is that components can listen to the event bus to understand when their operations are performed. For example, the Tab Panel component may listen for events indicating that it changes the active tab. Of course, this may be caused by clicking one of the tabs, so it is handled entirely within that component. However, with the event bus, some other elements can tell the tab to make changes. Imagine an error in which form submission causes the user to receive an alert in a specific tab, so the form sends a message to the event bus, instructing the tab component to change the active tab to a tab containing the error. This is how it looks on the event bus.
The pseudo-code for this case is as follows…
// Tab component Tabs.changeTab = id => { // Change the DOM operation of the active tab. }; MyEventBus.subscribe("change-tab", Tabs.changeTab(id)); // Other components... // Something happens, and then: MyEventBus.publish("change-tab", 2);
Do you need a JavaScript library to implement this? (Tip Question: You never need a JavaScript library). Well, there are many options:
- PubSubJS
- EventEmitter3
- Postal.js
- jQuery even supports custom events, which is highly relevant to this pattern.
Also, check out Mitt, a library with only 200 bytes of gzip. This simple pattern inspired people to solve it on their own in a way that was as concise as possible.
Let's do it ourselves! We don't use any third-party libraries at all, but instead take advantage of the event listening system that is already built into JavaScript, addEventListener
we are all familiar with and love.
First, some context
The addEventListener
API in JavaScript is a member function of EventTarget
class. The reason we can bind the click event to the button is that the prototype interface of ( HTMLButtonElement
) is indirectly inherited from EventTarget
.
Unlike most other DOM interfaces, you can use the new
keyword to create EventTarget
directly . It is supported in all modern browsers, but only recently. As we can see in the screenshot above, Node
inherits EventTarget
, so all DOM nodes have method addEventListener
.
Tips
I recommend using an extremely lightweight Node type as our event listening bus: HTML comments ( <!-- -->
).
For browser rendering engines, HTML comments are just comments in the code and have no functionality other than providing descriptive text to developers. However, since comments are still written in HTML, they end up appearing in the DOM as real nodes and have their own prototype interface— Comment
—which inherits from Node
.
The Comment
class can be created directly from new
, just like EventTarget
:
const myEventBus = new Comment('my-event-bus');
We can also use the ancient but widely supported document.createComment
API. It requires a data parameter, i.e. the content of the comment. It can even be an empty string:
const myEventBus = document.createComment('my-event-bus');
Now we can use dispatchEvent
to issue an event, which accepts an Event
object. To pass user-defined event data, use CustomEvent
, where the detail
field can be used to contain any data.
myEventBus.dispatchEvent( new CustomEvent('event-name', { detail: 'event-data' }) );
Internet Explorer 9-11 supports CustomEvent
, but no version supports new CustomEvent
. Using document.createEvent
to simulate it is complex, so if IE support is important to you, there is a way to populate it.
Now we can bind the event listener:
myEventBus.addEventListener('event-name', ({ detail }) => { console.log(detail); // => event-data });
If the event is intended to fire only once, we can use { once: true }
for one-time binding. Other options are not suitable here. To remove the event listener, we can use the native removeEventListener
.
debug
The number of events bound to a single event bus can be very large. If you forget to delete them, there may also be a memory leak. What if we want to know how many events are bound to myEventBus
?
myEventBus
is a DOM node, so DevTools in the browser can check it. There we can find the event in the Elements → Event Listener tab. Be sure to uncheck "Ancestor" to hide events bound to document
and window
.
Example
One disadvantage is that the syntax of EventTarget
is slightly verbose. We can write a simple wrapper for it. Here is a demonstration in TypeScript:
class EventBus<detailtype any> { private eventTarget: EventTarget; constructor(description = '') { this.eventTarget = document.appendChild(document.createComment(description)); } on(type: string, listener: (event: CustomEvent<detailtype> ) => void) { this.eventTarget.addEventListener(type, listener); } once(type: string, listener: (event: CustomEvent<detailtype> ) => void) { this.eventTarget.addEventListener(type, listener, { once: true }); } off(type: string, listener: (event: CustomEvent<detailtype> ) => void) { this.eventTarget.removeEventListener(type, listener); } emit(type: string, detail?: DetailType) { return this.eventTarget.dispatchEvent(new CustomEvent(type, { detail })); } } // Usage const myEventBus = new EventBus<string> ('my-event-bus'); myEventBus.on('event-name', ({ detail }) => { console.log(detail); }); myEventBus.once('event-name', ({ detail }) => { console.log(detail); }); myEventBus.emit('event-name', 'Hello'); // => Hello Hello myEventBus.emit('event-name', 'World'); // => World</string></detailtype></detailtype></detailtype></detailtype>
The following demonstration provides compiled JavaScript.
That's it! We just created a dependency-free event listening bus where one component can notify another component of changes to trigger an action. Doing such operations does not require a complete library, and the possibility of it being turned on is unlimited.
The above is the detailed content of Let's Create a Lightweight Native Event Bus in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

The article discusses using CSS for text effects like shadows and gradients, optimizing them for performance, and enhancing user experience. It also lists resources for beginners.(159 characters)

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

I was just chatting with Eric Meyer the other day and I remembered an Eric Meyer story from my formative years. I wrote a blog post about CSS specificity, and
