Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information from this source, I suspect that I may be encountering the same issue. However, I am unsure how to address it as I find the explanation in the linked question somewhat confusing.

class DragAndDrop {
    item: Item;
    documentBody: HTMLBodyElement;
    constructor(documentBody: HTMLBodyElement, item: Item) {
        this.documentBody = documentBody;
        this.item = item;
        this.documentBody.addEventListener("mousedown", this.onmousedown.bind(this));
    }
    onmousedown(event: MouseEvent): void {
        if (CollisionDetector.pointInRect(event.clientX, event.clientY, this.item)) {
            this.documentBody.addEventListener("mousemove", this.onMouseMove.bind(this));
            this.documentBody.addEventListener("mouseup", this.onMouseUp.bind(this));
        }
    }
    onMouseMove(event: MouseEvent): void {
        this.item.x = event.clientX;
        this.item.y = event.clientY;
    }
    onMouseUp(event: MouseEvent): void {
        this.documentBody.removeEventListener("mousemove", this.onMouseMove.bind(this));
        this.documentBody.removeEventListener("mouseup", this.onMouseUp.bind(this));
    }
}

Answer №1

If you're using the .bind method in your code, there are some issues to consider.

Challenges

  • .bind creates a duplicate of the function.

For example, foo.bind !== foo

Resolution

An alternative solution is to use arrow functions. Here's an example of how you can implement it for mousedown:

class DragAndDrop {
    item: Item;
    documentBody: HTMLBodyElement;
    constructor(documentBody: HTMLBodyElement, item: Item) {
        this.documentBody = documentBody;
        this.item = item;
        this.documentBody.addEventListener("mousedown", this.onmousedown);
    }
    onmousedown = (event: MouseEvent): void => {
        if (CollisionDetector.pointInRect(event.clientX, event.clientY, this.item)) {
            // Code continues here...
        }
    }
}

Further Information

To learn more about arrow functions, you can visit: https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

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

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Why is the server displaying a blank white page following the import of Material UI icons/module?

Here is the code snippet I am working on: import React from 'react' import "./Chat.css" import { Avatar, IconButton } from "@material-ui/core"; import SearchOutlinedIcon from '@mui/icons-material/SearchOutlined'; imp ...

Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage. After some research, I have discovered two methods for achieving this with Javascript: Method 1 WebDriver driver; // Assigned elsewhere Jav ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

What steps should I take to pinpoint the fundamental mistake in my webpage dedicated to clocks?

Exploring an intriguing clock project that utilizes ancient timekeeping methods found at . Recently encountered a puzzling error in Chrome, where it claims to be unable to call a method on undefined. Strangely enough, the error message is not located near ...

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

Guide to importing Bootstrap 5 bundle js using npm

Having some issues with implementing Bootstrap5 and NPM. The website design is using bootstrap, which works fine, but not all the JavaScript components (dropdowns, modals, etc). I want to figure out how to import the Bootstrap JS bundle without relying on ...

Encountering an issue when trying to retrieve the "createdAt" property in Cloud Code using the Parse Framework

I am working with Cloude Code to develop a more complex query, but I am having trouble accessing the automatically created "createdAt" property by Parse. Here is my code: Parse.Cloud.define("get_time", function(request, response) { var query = new Par ...

Tips for executing embedded scripts within templates

I am using a controller to display the Instagram embedded code <div class="instagram_here" [innerHtml]="instagram_embeded_code"></div> However, it is only showing a blank Instagram block. https://i.stack.imgur.com/gNPDL.png I suspect there m ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

Error: Compilation was unsuccessful due to module not found. Unable to resolve in ReactJS

As I was wrapping up this task, an unexpected error popped up: Module not found: Can't resolve './components/Post' in ./src/pages/index.js I've tried everything to troubleshoot it but no luck. Here's a rundown of my code snippets ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Loop proceeding without waiting for promise resolution containing nested Firebase call

I am currently facing an issue with making Firebase database calls within a loop and an outer Firebase call. The inner database call utilizes data returned from the outer call and the loop, hence it is nested inside the outer one. The goal is to set the re ...

Angular Universal involves making two HTTP calls

When using Angular Universal, I noticed that Http calls are being made twice on the initial load. I attempted to use transferState and implemented a caching mechanism in my project, but unfortunately, it did not resolve the issue. if (isPlatf ...

Disable the scroll animation feature for certain IDs

I implemented JavaScript code to animate scrolling for each block with a specific ID. However, when I added Bootstrap's tabs, the animation interfered with the functionality of the tabs. Is there a way to disable the scroll animation specifically for ...

Transforming an interactive HTML webpage into React/JSX

Imagine a scenario where I have two files: example.html <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="u ...

Avoid reloading the page in PHP when the browser back button is clicked

I've built an HTML form where the values are passed to a second page using POST method. On the second page, I have an edit button that, when clicked, redirects back to the HTML form page with the user's typed values. However, my dilemma is figuri ...

What could be causing the issue with Collection.find() not functioning correctly on my Meteor client?

Despite ensuring the correct creation of my collection, publishing the data, subscribing to the right publication, and verifying that the data was appearing in the Mongo Shell, I encountered an issue where the following line of code failed to return any re ...

My PayPal script (and all other JavaScript) was rendered dysfunctional by Onsen UI

I've been gradually incorporating Onsen UI into my existing web app. Currently, my home page file (index.jade) includes a splitter for navigation within the app. The splitter loads a NodeJS route that renders the requested page in jade. Everything wo ...