Why aren't my parameters getting passed through to a dispatched event?

MintDeparture picture MintDeparture · Oct 13, 2013 · Viewed 15.5k times · Source

I've set up an event listener like this...

window.addEventListener('message', parseMessage, false);

var parseMessage = function(rawMessage) {
    console.log(rawMessage.cmd);
};

And then I'm triggering the event like this:

var event = new Event('message', {'cmd':"blerg!"});

window.dispatchEvent(event);

The problem is the console.log in parse message is logging out undefined when I am expecting to to log out "blerg!"

What I am I doing wrong here with the events, how to I pass the 'cmd' message through to the event?

Answer

ComFreek picture ComFreek · Oct 13, 2013
  1. Use CustomEvent instead of Event for creating custom events.

  2. Specify your data in a 'details' object (see code).

  3. I changed the event name because message is also used for the postMessage API. It didn't cause problems when running in Chrome, but I wouldn't use it.

 

var parseMessage = function(rawMessage) {
  console.log(rawMessage);
  console.log(rawMessage.detail.cmd);
};

// changed event name
window.addEventListener('myMessage', parseMessage, false);

// data should be in a 'details' object
var evt = new CustomEvent('myMessage', {
    detail: {
      'cmd' : "blerg!"
    }
});

window.dispatchEvent(evt);

Here is an adjustment for IE >= 9 compatiblity (using document.createEvent() and CustomEvent::initCustomEvent()):

var evt = document.createEvent("CustomEvent");
evt.initCustomEvent('myMessage', false, false, {
    'cmd': "blerg!"
});