Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 16138  / 11 Years ago, sun, october 13, 2013, 12:00:00

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?


More From » events

 Answers
1

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

[#75020] Friday, October 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
2 Years ago
;