How can you remove an event listener in JavaScript without any specific condition?

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.

Answer №1

If you wish, you have the freedom to do as you please. However, it does not grant you the ability to remove the listener in the handler. Here is a brief example:

function adjustSize () {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    return adjustSize;
}

document.addEventListener('resize', adjustSize());

In this manner, you can invoke adjustSize for setup while linking the event. The function returns itself so that there is a reference for addEventListener after invoking adjustSize. Subsequently, when the event triggers, the return value is disregarded, as the handler will be executed from the event queue.

Alternatively, you may opt for an IIFE to set up the canvas.

const setSize = (function adjustSize () {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    return adjustSize;
}());

document.addEventListener('resize', setSize);

Ultimately, it is advised not to employ such maneuvers, as mentioned by Kaiido in the comments, "An elegant code is a code that is obvious". Simply call the function for setup. Eliminating the unnecessary return statement from the resize handler will result in a slight improvement in performance when updating the canvas.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unusual behavior observed during npm update operation

Just starting out with Angular and NPM, I have encountered a puzzling situation. I have two Angular-CLI projects. When I run npm update --save in one project, the dependencies (including @angular dependencies) are updated from version ^5.2.0 to ^5.2.3 in ...

Issue with page not refreshing upon closing/hiding modal

I'm struggling with my modal that is supposed to refresh the page once it's hidden. However, despite following what I believe is the correct code, it doesn't seem to be working as expected. Can anyone spot where the error might be? HTML: & ...

An error message stating 'The `uri` parameter passed to `openUri()` must be a ' is encountered, despite the variable being a string

I am trying to establish a connection between my database and my localhost using mongoose. However, I am encountering the following error: C:\Users\przyb\Desktop\JWT\node_modules\mongoose\lib\connection.js:520 t ...

A reliable approach for dynamically altering SVG graphics

It seems like IE10 does not support CSS transformations for SVGs, only attribute transformations. Here is an example: <svg><rect id="myrect" width="200" height="200"></rect></svg> setTimeout(function() { var r = document.getE ...

Achieve responsiveness for Google Chart Gauge

I am trying to create a Google Gauge chart that is web-responsive, but setting the width to '100%' is not working as expected. Here is the code I am using: <script type='text/javascript'> google.load('visualization&apo ...

Creating a Jest mock for Sendgrid in the __mocks__ directory

Here's my sendgrid code located in the __mocks__ directory: class MailService {} const mail = jest.fn( () => (MailService.prototype = { setApiKey: jest.fn(), send: jest.fn(), }) ); module.exports = mail; module.exports.MailS ...

css webpack react component not displaying background images

I'm facing an issue where I can't seem to get the image to display as a background. If I just attach the image directly, it shows up without any problems. However, my intention is to make it a background image so that I can overlay text on top of ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

Incorporate vanilla JavaScript and HTML into a Next.js application

I am facing an issue where I have a file that contains JavaScript and HTML code, which needs to be rendered within a Next.js application. The challenge is that the code in the file cannot be converted to JSX, and React Helmet does not seem to render anythi ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

Problem with navigating in AngularJs

I am encountering an issue with angularjs routing. My objective is to append different views based on the path. I aim to achieve this by using separate ng-apps within a single HTML document like so: <body> <div ng-app="header" id='header ...

The functionality of Angular's $window.scrollTo() seems to be malfunctioning

After successfully finding a specific element on my Angular app's page, I am attempting to scroll to it. However, despite trying both $window.scrollTo() and window.scrollTo(), the scrolling action is not being executed as expected. My console does log ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

What is the Method for Overriding a Remote Form Action URL?

On the website www.here.com/article1.htm, I have a script that populates a popup with an HTML login form that directs to www.not-here.com/login.php for authentication. Although the login process works correctly, once the action is completed, the browser re ...

Can you provide instructions on how to configure the npm settings to use the current directory in a pre

I'm currently working on setting the installation directory from where the user is installing to an npm config variable. This will help me reference it in my installation script. Can anyone advise if there is a command line solution for this or will ...

Tips for preloading an ENTIRE webpage

I am looking for a way to preload an entire web page using JavaScript in order to have it cached in the user's browser. While I know how to preload images with JS, my goal is to also preload the entire page itself. For example, on my website, there ...

Issue with MUI toggle switch not updating display and value upon clicking once

I'm currently experiencing issues with a Material UI toggle switch in my project. Initially, when the component loads, the console log displays the correct value. However, when I toggle the switch from 'yes' to 'no', the visual cha ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

Data binding in AngularJS allows for easy synchronization between the model and the view

I've been working on a simple AngularJS application that includes a form with two fields. However, I've run into an issue where I'm unable to read the values entered in these fields from my controller, as I keep getting 'undefined' ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...