Assuming multiple sliders can exist on a webpage and they each need their own state of user interactions like touch-start X-position and a boolean of whether it is currently processing a swipe or not..
I'm trying to reuse a piece of code that handles swipe and mouse drag events but each slider should have its own value of initalX and isInSwipe:
function slideInteractions(selector, callback) {
return function() {
let initialX = 0;
let isInSwipe = false;
document.querySelector(selector).addEventListener('mousedown', (ev) => {
startInteraction(ev);
ev.preventDefault();
});
document.querySelector(selector).addEventListener('touchstart', startInteraction);
document.addEventListener('mouseup', (ev) => {
endInteraction(ev, callback);
});
document.addEventListener('touchend', (ev) => {
endInteraction(ev, callback);
});
};
}
For each slider on the page I would use it like so, passing the slide container and the callback to call on accepted interaction:
slideInteractions('.project-slides', moveProject)();
I thought that since initialX and isInSwipe are defined in the function being returned then that would create a Closure over them so that each call of slideInteractions() would create its own copy of those variables but it seems that they go out of scope once the function returns.
Is there a way I can fix this keep the variables live on properly within the Closure?
EDIT
The variables are used in startInteraction() and endInteraction() but those functions don't really see those variables at all: they are undeclared within those functions which is where my confusion is because I assume that those functions would have access to the "closed" variables no?
initialXandisInSwipeare inside the returned function and they are copies, for each function call. But you never use them. Their scope is inside the function, as usual; see What is the scope of variables in JavaScript?.slideInteractionshas its owninitialXandisInSwipevariables. Where are you using those variables? It doesn't look like you are using them in the scope where they are defined, and that's likely the problem. Please provide more information.slideInteractionsfunction, but rather in the anonymous function that it returned. Which appears to be pretty pointless, if you don't even store it anywhere to call it multiple times or so.initialXorisInSwipeinmoveProject? Is that what you are asking about?startInteractionandendInteractionfunctions inside the anonymousfunctionin which these variables are defined. If this is not possible (because those functions need to be called also from elsewhere), then you must pass those values as arguments and get their new values back as return value.