wissel.net

Usability - Productivity - Business - The web - Singapore & Twins

By Date: November 2025

Higher Level Custom Events


A common occurence in web applications are button bars that execute various commands. So I was thinking of a pattern how to make this flexible and repeatable.

Separate Event and Actions

The typical setup we find is like:

const btn = document.querySelector('#myButton');
btn.addEventListener('click', (event) => {
  event.preventPropagation();
  // Business logic goes here
  doStuff();
});

This ties the logic to a low-level event of a low level component. To increase the usefulness we need to move from "mechanical" events to business level events, kind of.

An anology: imagine a fastfood kitchen. The cook gets orders "2 burgers, large fries" that don't contain: customer tapped on the order kiosk, drive thru order or delivery request. This information iss handled by the front-desk.

Similarly we can approach the button event. Instead tying our business logic to the click event, we tie it to a higher level event.

Components send events

const btn = document.querySelector('#myButton');
btn.addEventListener('click', (event) => {
  window.dispatchEvent(new CustomEvent('update-request', { detail: { button: btn }, bubbles: true, composed: true }));
});

This is oblivious where the business logic happens, while the logic still knows where it came from by inspecting the detail object. Decoupling using custom events makes testing easier.

window.addEventListener('update-request', updateStuff);
const updateStuff = async (event) => {
  await doStuff;
};

So far, so good. In the next installment I'll tie it together with a custom component.


Posted by on 13 November 2025 | Comments (0) | categories: Javascript WebComponents WebDevelopment