CustomEvent and EventTarget: let the parts of a WordPress script talk
The mini cart in the header should update when a product is added on the page, the counter in the sidebar too, and an analytics script wants to know about it as well. If the add-to-cart code calls all three directly, it has to know all of them, and removing the sidebar breaks the cart. Events decouple them: one part announces what happened, the others listen if they care. The browser has everything needed for that: CustomEvent and EventTarget.
Problem: The add-to-cart script of a theme calls updateMiniCart(), updateSidebarCount() and trackAddToCart() one after another. Each new feature adds another call, and a page without the sidebar throws ReferenceError.
Solution: Dispatch a CustomEvent named ha:cart-updated with the data in detail when the cart changes, let each component add its own listener, and for code that is not tied to the DOM use a separate EventTarget instance as a small event bus.
Dispatch and listen on the document
// add-to-cart part of the theme
function haCartUpdated( cart ) {
document.dispatchEvent( new CustomEvent( 'ha:cart-updated', {
detail: { count: cart.items_count, total: cart.totals.total_price },
} ) );
}
// mini cart, in its own file
document.addEventListener( 'ha:cart-updated', ( event ) => {
document.querySelector( '.ha-mini-cart__count' ).textContent = event.detail.count;
} );
// analytics, in another file
document.addEventListener( 'ha:cart-updated', ( event ) => {
window.dataLayer?.push( { event: 'cart_updated', items: event.detail.count } );
} );
The sender does not know who listens, and a page without the mini cart simply has one listener less. The prefix in the name (ha:) avoids collisions with events of other scripts; any string works as an event name. detail can hold any value, but treat it as read-only in listeners: all of them get the same object.
Events that bubble from an element
When the event belongs to a specific element, dispatch it there and let it bubble:
// inside a product card component
card.dispatchEvent( new CustomEvent( 'ha:variant-change', {
bubbles: true,
detail: { productId: Number( card.dataset.productId ), variationId },
} ) );
// one listener for all cards on the page
document.querySelector( '.ha-products' ).addEventListener( 'ha:variant-change', ( event ) => {
haUpdatePrice( event.target, event.detail.variationId );
} );
bubbles: true is needed for that, custom events do not bubble by default. A listener on a parent element handles all cards, including those added later by infinite scroll, the same idea as event delegation for clicks: event delegation. Inside a Shadow DOM, add composed: true so that the event leaves the shadow root.
An event bus without the DOM
// js/bus.js export const haBus = new EventTarget();
// js/autosave.js
import { haBus } from './bus.js';
export function haSaved( postId ) {
haBus.dispatchEvent( new CustomEvent( 'saved', { detail: { postId } } ) );
}
// js/notices.js
import { haBus } from './bus.js';
const onSaved = ( event ) => haShowNotice( `Post ${ event.detail.postId } saved` );
haBus.addEventListener( 'saved', onSaved );
// later: haBus.removeEventListener( 'saved', onSaved );
new EventTarget() has worked in all browsers since 2019. A separate bus keeps internal events of a plugin away from the global document, where every script can see and fire them. To remove a listener, keep a reference to the same function; an inline arrow function cannot be removed. Listeners that should run once take { once: true }, and listeners that belong to a component that can be destroyed take an AbortSignal:
const controller = new AbortController();
haBus.addEventListener( 'saved', onSaved, { signal: controller.signal } );
controller.abort(); // removes every listener registered with this signal
How ES modules like these are loaded in WordPress: ES modules, import and export.
jQuery events and WooCommerce
WooCommerce’s own scripts trigger jQuery events such as added_to_cart on document.body. Those are jQuery-only and do not reach addEventListener. A bridge forwards them once:
jQuery( document.body ).on( 'added_to_cart removed_from_cart', ( event, fragments, cartHash ) => {
document.dispatchEvent( new CustomEvent( 'ha:cart-changed', { detail: { type: event.type, cartHash } } ) );
} );
The rest of the code then listens to the native event and does not need jQuery. The Cart and Checkout blocks do not use these jQuery events; there the cart state lives in the wc/store/cart data store.
NOTE: dispatchEvent() is synchronous: all listeners run before it returns, and an error in one listener does not stop the others but is reported in the console. Events are for “this happened” messages. For “give me a value” calls, a function or a store is the better tool.