Ad

Window.addEventListener('message', MyFunction(event)) Doesn't Work

- 1 answer

I'm trying to understand why the following does not work.

var myFunction = function(event) {
    // do something with event
};

window.addEventListener('message', myFunction(event));

I get the following error: "ReferenceError: event is not defined".

However, the following works and event is able to be used.

window.addEventListener('message', function(event) {
    // do something with event
});

How can I use event in the first situation? Why is event only accessible in the second situation?

Ad

Answer

You are seeing the error because you are invoking the function immediately. You need to pass a reference to the function instead.

In other words, change this:

window.addEventListener('message', myFunction(event));

to this:

window.addEventListener('message', myFunction);

When using the addEventListener() method, the event object will be passed as the first parameter by default when the event is fired.

Ad
source: stackoverflow.com
Ad