Talking about "this" within the event function and how to remove the TypeScript event reference

Currently, I am working on developing a TypeScript game and facing some challenges with adding and removing a "keydown" event. The event function is currently referencing the document when I actually need it to refer to the object instance.

Is there a way to achieve this?

class Player {
    board: Board = new Board();
    pice: Pice = new Pice();

    constructor() {
        this.registerKeyEvents();
    }

    registerKeyEvents(): void {
        document.addEventListener("keydown", this.handleKeyPress);
    }

    unregisterKeyEvents(): void {
        document.removeEventListener("keydown", this.handleKeyPress);
    }

    handleKeyPress(event: KeyboardEvent): void {
        console.log(this); // #document

        switch (event.keyCode) {

            // Left
            case 37:
                this.pice.move(-1, 0, this.board);
                break;
        }

    }

}

Answer №1

To ensure the proper context is maintained, you can either bind the function to the instance or use an arrow function.

// Using binding.
class Player {
    constructor() {
        this.addKeyEvents();
        // Bind the function to `this` context.
        this.keyClick = this.keyClick.bind(this)
    }

    addKeyEvents(): void {
        document.addEventListener("keydown", this.keyClick);
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}

// Using arrow function.
class Player {
    constructor() {
        this.addKeyEvents();
    }

    addKeyEvents(): void {
        // Use an arrow function to maintain the context.
        document.addEventListener("keydown", event => this.keyClick(event));
    }

    keyClick(event: KeyboardEvent): void { /* ... */ }
}

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

Creating a dashed line for a circle in SVG by using the path element

Currently, I am facing a challenge where I need to create a circle using multiple points that are very close together. For reference, you can view the jsfiddle link provided below: http://jsfiddle.net/L6e5oz3L/ <path style="" stroke-dasharray="10 5" f ...

Halting the execution of a jQuery function when a condition is true

Currently in the process of building a website for my new brand, I am faced with a challenge while working with jQuery for the first time. Specifically, I am encountering issues related to the state of a specific div. The code contains if statements that ...

Is it appropriate for HTML5 Web Workers to utilize CORS for cross-origin requests?

As I was creating a hosted API that relies on web workers, I encountered an intriguing issue. I am looking for feedback from the community to help me with this. Even though my server has the necessary CORS headers in place to serve the worker JS files and ...

When the C# method is executed, jQuery is reset

One feature I have on my website is a "newsletter" widget that expands when the user clicks a button. Inside the expanded section, there is an input box for email address and a submit button. The code behind this functionality verifies the email format and ...

Display the QWebEngineView page only after the completion of a JavaScript script

I am currently in the process of developing a C++ Qt application that includes a web view functionality. My goal is to display a webpage (which I do not have control over and cannot modify) to the user only after running some JavaScript code on it. Despit ...

Problem with Jquery Colorbox in firefox

I am using JavaScript to dynamically populate anchor links in a repeater and displaying them in a colorbox iframe. This functionality is working well in IE7, Safari, and Chrome, but encountering an issue in Firefox (version 14.1). In Firefox, the links ar ...

What is the reason for not dynamically passing all values in HTML with Vue JS?

Working with Vue.js and Laravel is my current setup. I am able to successfully pass a few variables through the Vue.js component template, but some of them are not being passed and show up as empty strings (""). HTML (Template): <template v-if="sho ...

Creating a text slider in Javascript with dual quote sets is a fun and interactive

I am looking to create a dynamic quotes text slider with two sets of data. For reference, check out the fiddle link here: https://jsfiddle.net/628r3t1h/ (function() { var quotes = $(".quotes"); var quoteIndex = -1; function showNextQuote( ...

Creating a new row dynamically in reactable is a useful feature that can enhance the

My goal is to add a new row when clicking on an accordion, specifically while expanding using reactable. I have included the expected outcome below. I have displayed structured data in a table using Tr and Td from reactable, but I am uncertain how to add t ...

"Redirecting using parameters upon pressing the enter key: A step-by-step guide

I've been pondering about the best way to redirect to a specific site while including query parameters in the URL. <input id="query" name="query" placeholder="Search" type="input" > I have experimented wi ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

What is preventing the JQuery dialog from opening?

When I try to trigger a dialog box by pressing the enter key, it is not working as expected. Instead of opening the dialog, it just hides the text. Can someone help me understand what might be causing this issue? <!doctype html> <html lang="en" ...

The ng-disabled feature restricts the input of multiple texts into a text box within an ng-repeat loop

Just wanted to share an issue I'm facing with ng-disable in a fiddle. I've been trying to disable all input text boxes that already have a value, but the problem is that when I try to enter a value into a textbox that doesn't have one, it ge ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Generate tables and rows dynamically

I am looking for guidance on dynamically creating a table and adding rows to it. I have successfully created a table with one row containing form fields, but I am unsure how to add additional rows. Any examples or suggestions on how this can be implemented ...

What is the best location to store common utility functions that will be utilized by various Vue.js components?

Typically, I create functions within the component that will use them. However, I am finding that I need to use a particular function in multiple components now. Currently, I would have to duplicate and paste the function into each component, which is not ...

Display a loading component within the navbar in React while waiting for data to be retrieved

I recently updated my navbar component to accept dynamic values for menu titles. One of these dynamic values is the username, which needs to be fetched asynchronously. To handle this, I decided to display a loading animation until the username is fully fet ...

Displaying an animated loading gif as the form is submitted

How can I get my form to submit and display an alert upon submission when using the following JS on a button with class "submit"? $( ".submit" ).click(function( event ) { if(some checks){ ... }else{ ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Attempting to capture user keyboard input in TypeScript in order to transfer it to the Python script

Greetings! I'm in the process of developing a simple code that captures keyboard input from a typescript file and transmits it to a separate python file. The data transmission appears to be successful as I receive a message in the python terminal when ...