Here is the code snippet that I am currently working with:
function setSize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.addEventListener('resize', setSize)
}
The issue arises when the setSize()
function is recursively called by the resize
event listener. This results in multiple event listeners being added, causing problems when handling window resizing.
To avoid stacking event listeners, I need a way to remove the previous event listener on each recursion. The challenge lies in achieving this without specifying an event
parameter in the removeEventListener()
method.
function setSize() {
document.removeEventListener(setSize) // An ideal solution
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.addEventListener('resize', setSize)
}
Is there a more elegant approach or alternative technique that you would recommend for solving this problem?
Edit:
I am looking for a streamlined solution that can handle initial setup and subsequent window resizes within a single function, rather than having to define setSize()
, call it explicitly, and then create an event listener separately.
function setSize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
// I'd prefer not having to do this:
setSize()
document.addEventListener('resize', setSize)
// Seeking a more efficient solution that caters to both scenarios seamlessly.
After posting my question, I realized that the specificity of the event
parameter in removeEventListener()
was necessary because it indicates the exact event triggering the removal. My intent, however, is to immediately remove the event listener upon reading the code.