Listener lifetime: once, passive and signal
Quick answer
The options object controls listener behavior. once: true removes the listener before its first invocation. passive: true promises not to cancel the event; preventDefault has no effect in that callback. signal ties removal to an AbortSignal; aborting the controller removes the listener. An already aborted signal prevents registration.
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 b=document.createElement("button");let n=0;b.addEventListener("click",()=>n++,{once:true});b.click();b.click();console.log(n);Expected console output:
1The listener is removed before its first call.
const b=document.createElement("button"),c=new AbortController();let n=0;b.addEventListener("click",()=>n++,{signal:c.signal});b.click();c.abort();b.click();console.log(n,c.signal.aborted);Expected console output:
1 trueAbort removes the listener for subsequent events.
Common mistake
Do not use passive on a listener that must cancel a default action. Aborting a listener does not undo work it already performed.
Practice
Attach two handlers with one signal and verify that abort removes both.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Listener lifetime: once, passive and signal — Knowledge Check
Apply the concept and predict the browser example behavior.
Which option makes a listener run at most once?
What happens if a passive listener calls preventDefault?
What happens on registration with an already aborted signal?
What is the exact console output in Listener lifetime: once, passive and signal example 1?
const b=document.createElement("button");let n=0;b.addEventListener("click",()=>n++,{once:true});b.click();b.click();console.log(n);What is the exact console output in Listener lifetime: once, passive and signal example 2?
const b=document.createElement("button"),c=new AbortController();let n=0;b.addEventListener("click",()=>n++,{signal:c.signal});b.click();c.abort();b.click();console.log(n,c.signal.aborted);