简体   繁体   中英

Event Listener with anonymous function

It's written on the MDN that

If you want to pass parameters to the listener function, you may use an anonymous function.

After some experimentation I figured out when I try to register an event listener with a one-parameter function like this (without an anonymous function)

target.addEventListener(type, doSomething(parameter));

the listener function executes even when an event didn't happen, but when I wrap it up in an anonymous function

target.addEventListener(type, function () {doSomething(parameter);});

everything goes as expected.

Why does such behavior take place? I guess it is somehow connected with closures.

When defining the handler function like so

target.addEventListener(type, doSomething(parameter));

You are passing the function's return value as handler. For example consider this function:

function doSomething(event) {
    return 'foo';
}

Now, the function gets executed immediatly, before the event has happened, and you are basically just passing this as handler:

target.addEventListener(type, 'foo');

That can't work.

The second example

target.addEventListener(type, function () {doSomething(parameter);});

correctly passes a function as reference, without having it executed before the event occurred.

When you write "doSomething(parameter)" you are actually invoking the function and then the return value of the function is the result and that result is passed to addEventListener. "doSomething(parameter)" is executed, it is not a function pointer like what you actually want (although javascript has no visible function pointers).

If you wrote target.addEventListener(type, doSomething); that would actually pass the function as a parameter like you want. However, it wouldn't pass the paramter into that function call like you want. That's why you need to wrap it like you did. If you want to so something like what you wanted, you would do:

function doSomethingWrapper() {
    doSomething(parameter);
}

target.addEventListener(type, doSomethingWrapper);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM