Combining EventListener and Closures in Javascript

Markus STZ

I am trying to use a closure, to call a function when the user scrolls on the document in JavaScript. Therefore i create the constant scroll and call the inner function via scroll() when the event 'scroll' happens. I don't get an error when I'm trying to do this with the code below but the inner function doesn't get called for some reason.

const scroll = scrollEvent();
document.addEventListener("scroll", scroll());

function scrollEvent() {
    debugger;
    var positions = {pos1: 3, pos2: 5};
    return function() {
        loadContent(positions);
    }
}

Thanks in advance for your help.

Teemu

You've almost the correct code. But the closure is already created when you create scroll variable and call scrollEvent (after that scroll contains a reference to the returned function), hence you have to pass only scroll to addEventListener, because calling it just returns undefined.

Another way is to omit scroll variable, and call scrollEvent in the argument, like so:

document.addEventListener("scroll", scrollEvent());

Now scrollEvent returns the function to use as an event listener, and the closure is created, and positions is available in the event handler when the event fires.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related