Skip to content
Astera Technology

Keep event detail separate from a copied snapshot

Compare event.detail identity with the payload supplied at construction.

Download complete case notes and answer keys ↓

Trace the fixed program

A local EventTarget receives a payload titled Draft. Its listener checks reference identity and changes detail.title to Revised. Inspect the original payload afterward.

Complete original program
const target=new EventTarget();const payload={title:'Draft'};let same;
target.addEventListener('sample',event=>{same=event.detail===payload;event.detail.title='Revised';});
target.dispatchEvent(new CustomEvent('sample',{detail:payload}));
console.log(JSON.stringify({same,title:payload.title}));
Exact console output
{"same":true,"title":"Revised"}
Values and execution
InspectionResultMeaning
event.detail===payloadtrueSame object
payload.title after listenerRevisedListener changed original

Explain the result

CustomEvent stores the supplied detail value. Dispatch does not clone it, and this listener mutates the original object through the same reference. Copying an outer object before construction separates these primitive fields only; nested objects still need their own copy policy.

Test the alternative

Treating detail as a protected historical snapshot would lose Draft. The repaired fixture passes a copy for these flat fields; the listener can then change its copy without changing payload.

Separate finite alternative
const target=new EventTarget();const payload={title:'Draft'};let same,eventTitle;
target.addEventListener('sample',event=>{same=event.detail===payload;event.detail.title='Revised';eventTitle=event.detail.title;});
target.dispatchEvent(new CustomEvent('sample',{detail:{...payload}}));
console.log(JSON.stringify({same,title:payload.title,eventTitle}));
Alternative output
{"same":false,"title":"Draft","eventTitle":"Revised"}

Work the boundary case

Would {...payload} also isolate a nested payload.style object?

Show the worked answer

No. A shallow outer copy still shares style. Copy the edited branch or use a suitable snapshot strategy for the actual value types.

Fresh boundary program
const target=new EventTarget();const payload={style:{ink:'green'}};let sameStyle;
target.addEventListener('sample',event=>{sameStyle=event.detail.style===payload.style;event.detail.style.ink='purple';});
target.dispatchEvent(new CustomEvent('sample',{detail:{...payload}}));
console.log(JSON.stringify({sameStyle,ink:payload.style.ink}));
Boundary output
{"sameStyle":true,"ink":"purple"}

Original example files