Dispatch event with data

63,569

Solution 1

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

Solution 2

Unfortunately CustomEvent not work on IE (before Edge), but you can simply use the normal Event.

Just consider that also Event is an object, and so you can add all custom attributes you need:

 event.X = "foo";

On this way you can check your custom field on the callback function joned to the event.


NB. For old IE version you need this polyfill for new Event missed function:

var event;
if(typeof(Event) === 'function') {
  event = new Event(EVENT_NAME);
}else{
  event = document.createEvent('Event');
  event.initEvent(EVENT_NAME, false, false);
}
Share:
63,569
nicholaswmin
Author by

nicholaswmin

Nikolas Kyriakides

Updated on July 05, 2022

Comments

  • nicholaswmin
    nicholaswmin almost 2 years

    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"
    })
    
  • adnan kamili
    adnan kamili almost 10 years
    @NicholasKyriakides does this happen in all the browsers can you please update your code using what I suggested or create a fiddle
  • adnan kamili
    adnan kamili almost 10 years
    @NicholasKyriakides what does alert display in my updated code.
  • adnan kamili
    adnan kamili almost 10 years
    @NicholasKyriakides check my updated answer for multiple variables
  • nicholaswmin
    nicholaswmin almost 10 years
    I think you forgot a } in detail but other than that it works like a charm. Many thanks again