Custom events in JavaScript
Your own event type, with a payload, bubbling like any other.
function announce(element, stars) {
const event = new CustomEvent("step:cleared", {
detail: { stars, at: Date.now() },
bubbles: true,
cancelable: true,
});
const proceeded = element.dispatchEvent(event);
return { proceeded, defaultPrevented: event.defaultPrevented };
}
function listen(root) {
root.addEventListener("step:cleared", (event) => {
if (event.detail.stars < 1) event.preventDefault();
});
}
How it works
detailcarries the payload.bubblesdecides whether an ancestor can hear it.preventDefaultworks if the event is cancelable.
Keywords and builtins used here
Dateconstfunctionifreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 403
- Tokens
- 101
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.
Step 3 of 3 in Events, step 6 of 13 in The browser.