Dispatch event with data

nicholaswmin picture nicholaswmin · May 18, 2014 · Viewed 55.9k times · Source

I'd like to dispatch an event that will pass some data to any event listeners that listen on that event.

Considering a function that fires an event:

function click() {
  const x = 'foo'
  document.dispatchEvent(new CustomEvent('clicked'))
}

click()

How can I pass custom data to the event listener?

document.addEventListener('clicked', function(e) {
  console.log(x) // logs "foo"
})

Answer

adnan kamili picture adnan kamili · May 18, 2014

Perhaps you are looking for event.detail

new CustomEvent('eventName', {'detail': data})

Instead of data use x and in event listener you can access x using event.detail

function getSelectionBounds() {
  var x = (bounds["x"].toFixed(2));
  var y = "xyz";
  var selectionFired = new CustomEvent("selectionFired", {
    "detail": {"x":x,"y":y }
  });

  document.dispatchEvent(selectionFired);
};

document.addEventListener("selectionFired", function (e) {
  alert(e.detail.x+"   "+e.detail.y);
});