Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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!"
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...