I'm working in a project with a soft page transition and multiple modules. On every transition the removeEventListeners() function in each module is called.
How do I kill all performance-consuming processes? In this case the mousemove listener and the requestAnimationFrame.
I know I can remove the listener of the mousemove event by using a function instead of the arrow function in the addEventListener. But then how do I manipulate the xmouse and ymouse values?
export default class Cursor extends Core {
init() {
let xmouse;
let ymouse;
const friction = 0.125;
this.$el.addEventListener('mousemove', (e) => {
xmouse = e.clientX || e.pageX;
ymouse = e.clientY || e.pageY;
});
let x = 0;
let y = 0;
let dx = 0;
let dy = 0;
const followMouse = function followMouse() {
requestAnimationFrame(followMouse);
if (!x || !y) {
x = xmouse;
y = ymouse;
} else {
dx = (xmouse - x) * friction;
dy = (ymouse - y) * friction;
if (Math.abs(dx) + Math.abs(dy) < 0.1) {
x = xmouse;
y = ymouse;
} else {
x += dx;
y += dy;
}
}
cursor.style.left = `${x}px`;
cursor.style.top = `${y}px`;
};
followMouse();
}
}
removeEventListeners() {
// Kill all performance-consuming processes of this module.
// this.$el.removeEventListener('mousemove'); <- there's no function to be removed.
// cancelAnimationFrame(followMouse); <- followMouse does not exist here
}
}