Event vs CustomEvent
CustomEvent can send data through 'detail' property, but Event can not do that;
Event
const eventInstance = new Event(':eventName');
// add event on document
document.addEventListener(':eventName', (e) => {
// TODO
console.log(e);
});
// trigger event
document.dispatch(eventInstance);
CustomEvent
const customEventInstance = new CustomEvent(':customEventName');
// add event on document
document.addEventListener(':customEventName', (e) => {
// TODO
console.log(e);
});
// trigger event
document.dispatch(customEventInstance);
What if you want to trigger an event with params or data
Only CustomEvent can do this
const customEventInstance = new CustomEvent(':customEventName', {
detail: {
data: 'your data',
name: 'Tio'
}
});
// add event on document
document.addEventListener(':customEventName', (e) => {
// TODO
// You can get data or name from e.detail object
console.log(e.detail); // { data: 'your data', name: 'Tio' }
});
// trigger event
document.dispatch(customEventInstance);
댓글