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?