#(Javascript/Typescript) EventListener callback is modifying class field members, yet not uniformly

13 messages · Page 1 of 1 (latest)

stable epoch
#

Hello, I have a class that encapsulates a document element and registers EventListeners for said element. The idea is that the callbacks from events will modify public field members which will then be accessible to other parts of the application. However, all modifications inside of the callback functions are not propagating to field members when accessed outside of the callbacks. I.e. If I set zoom (a field member) to be 4.0 in the callback and later call getZoom() public member function in some other part of my code, it returns 1.... What am I doing wrong?

code :

export class Canvas {
    private canvas: HTMLCanvasElement
    private view: mat4 = mat4.create();

    private zoom: number = 1;
    private camPos: number;

    constructor() {
        console.log("canvas constructed");
        this.canvas = document.getElementById("c") as HTMLCanvasElement;
        this.canvas.addEventListener('wheel', this.handleScroll);
        this.canvas.addEventListener('click', this.handleClick);
    }

    private handleScroll(event: WheelEvent) {
        if(event.deltaY != 0) {
            if(this.zoom == undefined || this.zoom == 0) {
                this.zoom = 1;
            }

            this.zoom += (event.deltaY / Math.abs(event.deltaY)) * -0.1; //zoom sensitvity
            this.zoom = Math.min(Math.max(0.125, this.zoom), 4); //restrict the zoom level here
        }

        console.log(`zoom : ${this.zoom}`)
        console.log(`view : ${this.view}`)
    }

    private handleClick() {
        console.log("canvas clicked!")
    }

    public resizeCanvasToDisplay() {
        this.canvas.width = this.canvas.clientWidth;
        this.canvas.height = this.canvas.clientHeight;
    }

    public getCanvas() {
        return this.canvas;
    }


    public getView() { 
        console.log(this.zoom) //this is returning 1 always....
    }
}

#

!helpers

near siloBOT
#

:warning: Please wait a bit longer. You can ping helpers <t:1684080333:R>.

young flame
# stable epoch !helpers

the !helpers command is meant is meant to remind helpers if your thread has been inactive or hasn''t got any response for a long period of time
just give ppl some time to read your message and come up with a solution

stable epoch
#

my bad

#

got it working

young flame
#

need to bind the method to the right this?

stable epoch
#

for some reason, according to stackOverflow and ChatGPT, it says this.function.bind(this) should work

young flame
#

yeah

stable epoch
#

but that didn't work

#

I had to do

#

(event) => { this.handleScroll(event) }

#

which is annoying