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.
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}));
{"same":true,"title":"Revised"}| Inspection | Result | Meaning |
|---|---|---|
| event.detail===payload | true | Same object |
| payload.title after listener | Revised | Listener 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.
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}));
{"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.
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}));
{"sameStyle":true,"ink":"purple"}