Custom events between components
Let one part announce something and others listen, without them knowing each other.
JavaScript · Custom events between componentsIntermediate
document.addEventListener('cart:add', (e) => {
console.log('Added', e.detail.name);
});
function addToCart(item) {
document.dispatchEvent(new CustomEvent('cart:add', { detail: item, bubbles: true }));
}
addToCart({ name: 'Pen', qty: 2 });CustomEventdispatchEventdecoupling