Tc_ February 2016

Can't remove eventlisteners TypeScript/OOP JavaScript

The onMouseUp is fired, but it doesn't remove the EventListeners. I've read a lot of post where people are having trouble, and it's because they don't remove the same function as they add, and reading this I'm thinking that I might have the same problem, but how do I deal with it? I don't fully understand the answer on the linked question.

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));
    }
}

Answers


basarat February 2016

In your code you use .bind.

Issues

  • .bind creates a copy of the function.

i.e. foo.bind !== foo

Solution

Use an arrow function. I do it for mousedown for you:

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)) {
            // Similarly ...
        }
    }
}

More

More on arrow functions : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

Post Status

Asked in February 2016
Viewed 1,898 times
Voted 9
Answered 1 times

Search




Leave an answer