Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 961
MintDeparture Avatar asked Oct 13 '13 12:10

MintDeparture


2 Answers

  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!"
});
like image 81
ComFreek Avatar answered Oct 22 '22 09:10

ComFreek


For IE9/10 polyfill you can use this code provided by Mozilla:
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

(function () {
  if (
      typeof window.CustomEvent === "function" ||
      // In Safari, typeof CustomEvent == 'object' but it otherwise works fine
      this.CustomEvent.toString().indexOf('CustomEventConstructor')>-1
  ) { return; }

  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   }

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();

Also described here but with wrong URL: https://stackoverflow.com/a/22946340/1736012

like image 28
olefrank Avatar answered Oct 22 '22 08:10

olefrank