Dispatch custom application events
Quick answer
Use CustomEvent(type, {detail, bubbles, cancelable}) to communicate a meaningful application occurrence. detail holds payload data; ordinary Event does not provide that field. dispatchEvent(event) runs the event listeners synchronously and returns whether the event was not canceled. Bubbling defaults to false; choose it deliberately, and do not treat synthetic events as proof of user intent.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const p=document.createElement("div"),b=document.createElement("button");p.append(b);p.addEventListener("stock-change",e=>console.log(e.detail.qty));b.dispatchEvent(new CustomEvent("stock-change",{detail:{qty:4},bubbles:true}));Expected console output:
4The custom event bubbles with its payload.
const t=new EventTarget();t.addEventListener("ready",()=>console.log("listener"));console.log("before");t.dispatchEvent(new Event("ready"));console.log("after");Expected console output:
beforelistenerafterThe listener runs before dispatchEvent returns.
Common mistake
CustomEvent is not an asynchronous message queue. Avoid passing sensitive data unnecessarily because other listeners may inspect it.
Practice
Dispatch an inventory-change event carrying a small quantity and let a parent listener update a status element.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dispatch custom application events — Knowledge Check
Apply the concept and predict the browser example behavior.
Which CustomEvent option carries application data?
What is the default value of bubbles for a newly constructed CustomEvent?
When do listeners run during dispatchEvent?
What is the exact console output in Dispatch custom application events example 1?
const p=document.createElement("div"),b=document.createElement("button");p.append(b);p.addEventListener("stock-change",e=>console.log(e.detail.qty));b.dispatchEvent(new CustomEvent("stock-change",{detail:{qty:4},bubbles:true}));What is the exact console output in Dispatch custom application events example 2?
const t=new EventTarget();t.addEventListener("ready",()=>console.log("listener"));console.log("before");t.dispatchEvent(new Event("ready"));console.log("after");