본문 바로가기
✘✘✘ Javascript

Event vs CustomEvent && How to trigger event with data

by PrettyLog 2022. 6. 27.

CustomEvent image

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);

ref custom event in javascript

댓글