Nicholas Kyriakides Nicholas Kyriakides - 7 months ago 51
Javascript Question

Dispatch event with data

I am trying to dispatch an event from a function that will pass some data to the event listener.

Here is my code:

function getSelectionBounds() {
var x = bounds.x.toFixed(2);
var selectionFired = new CustomEvent("selectionFired",{ "detail": "Something was selected" });

document.dispatchEvent(selectionFired);
}


and this is the event listener.

document.addEventListener("selectionFired", function (e) {
console.log(x);
});


I would like to pass
x
as data from the event dispatcher to the event listener.

Answer

If you make "x" a global variable, it will solve your problem. Perhaps you are looking for event.detail

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

Instead of data use x and in event listenener 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);
});