The 'This' keyword within the paper.js event is utilized in the constructor

I recently attempted to integrate paper.js with TypeScript.

My goal was to add event handlers to the constructor of my PenTool class (in order to use dependency injection and define all paper events during the creation of the tool).

Here is a snippet of the code I have:

export class PenTool implements BaseTool {

name: string;
toolType: Tools;
tool: any;
drawingContext: any;
path: any;

constructor(private paperService: PaperService) {

    this.name = "Pen";
    this.toolType = Tools.Pen;
    this.drawingContext = this.paperService.getDrawingContext();

    this.tool = new this.drawingContext.Tool();

    this.tool.onMouseDown = function (event) {
    
        //!!!!!!!!!!!!!!!!!!!
        //I want to use my class property here (this.name) or
        //(this.drawingContext) etc, but I can't!

        this.path = new (paperService.getDrawingContext()).Path();
        //this.path = new this.drawingContext.Path();
        this.path.add(event.point, event.point);
        this.path.strokeColor = 'black';
    }

    this.tool.onMouseDrag = function (event) {

        console.log('pen -> mouse drag!');

        if (event.modifiers.shift) {
            this.path.lastSegment.point = event.point;
        } else {
            this.path.add(event.point);
        }
    }
}

}

The paperService provides access to the paper variable and creates a new paperScope, among other things. The issue I'm facing is that I can't access class properties within the event functions.

What am I doing wrong? Thank you in advance.

Answer №1

Opt for arrow functions to maintain the context.

export class PenTool implements BaseTool {

  name: string;
  toolType: Tools;
  tool: any;
  drawingContext: any;
  path: any;

  constructor(private paperService: PaperService) {

    this.name = "Pen";
    this.toolType = Tools.Pen;
    this.drawingContext = this.paperService.getDrawingContext();

    this.tool = new this.drawingContext.Tool();

    this.tool.onMouseDown = (event) => {

      //!!!!!!!!!!!!!!!!!!!
      //I want to utilize my class property here (this.name) or
      //(this.drawingContext) etc, but I can't!

      this.path = new(paperService.getDrawingContext()).Path();
      //this.path = new this.drawingContext.Path();
      this.path.add(event.point, event.point);
      this.path.strokeColor = 'black';
    }

    this.tool.onMouseDrag = (event) => {

      console.log('pen -> mouse drag!');

      if (event.modifiers.shift) {
        this.path.lastSegment.point = event.point;
      } else {
        this.path.add(event.point);
      }
    }
  }

}

This article provides a plethora of details on how this operates in javascript.

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

Ways to track activities involving a specific input element

Currently, I'm dealing with an input field within an ASPX page utilizing minified JavaScript. Unfortunately, I do not have access to the C# source code for this particular page as it is not publicly available. However, I can still make changes to the ...

Create a Referral Program page within a swapping interface similar to the functionalities found in platforms like PancakeSwap, PantherSwap, and

Currently, my goal is to create a referral program page similar to the one found at . I have explored the source code on GitHub for the PantherSwap interface, but unfortunately, I did not come across any references to that specific section. Would you be ...

Troubleshooting type inference challenges following class inheritance in TypeScript

Imagine a scenario where you have a class called Base. In this class, the print method requires a parameter that merges IBaseContext with a generic type T. interface IBaseContext { a: number } class Base<T> { public print(context: IBaseContext & ...

Declaring an array that holds Angular components in Angular 11: What's the best approach?

I'm trying to implement a feature in my Angular component where I can create a list that displays content from other components. My current approach involves declaring an array that contains references to different Angular components: import { Compone ...

Return a dynamic interface type with C#'s Simple Injector

Two data provider classes, Provider1 and Provider2, were created with implementation of an IProvider interface. The method GetProvider() was designed to return the specific implementation of the interface based on certain conditions: public IProvider GetP ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

Creating mock objects for Karma/jasmine testing in Angular

Could someone offer a detailed explanation on how to generate Stubs for mocking services in Angular Karma testing? I would greatly appreciate either a comprehensive example or a helpful link. Once the stub is created, what's the best way to write tes ...

Exploring the depths of useDispatch and dispatch in React-Redux

I am currently analyzing the code written by a former colleague of mine. Based on my understanding, useDispatch accepts an object containing the action type and payload, which is then compared to all reducers to update the state accordingly. However, in t ...

Instantiate an object of a class using its name stored in a string variable

I am seeking information on a potential solution that I am unsure about. I am interested in finding out if it is possible and, if so, how it can be done. Here is my query: My scenario involves custom model classes that I have created - such as Customer, E ...

What is the best way to ensure TypeScript knows there are no null values in this array?

As I transition from JavaScript to TypeScript, I have encountered a situation with filtering null values from an array. In JavaScript, I would typically use .filter(x => x) to achieve this. However, in TypeScript, it is asking me to specify that the arr ...

Preventing Cross-Site Request Forgery (CSRF) in ASP.NET Core: Best

Found motivation from: Methods to prevent CSRF attacks in ASP.NET MVC 4? Can the equivalent outcome be attained in ASP.NET Core? ...

Sign up the lambda function as a factory (including dependencies)

Currently, I am in the process of transitioning from the Grace IOC container to Autofac. Previously, with Grace, I was able to register like this (see original source): block.ExportFactory<SimpleObjectA, SimpleObjectB, SimpleObjectC, IEnumerable<ISi ...

Angular 2 does not automatically re-evaluate *ngIf on model change

I am working on a navigation bar that consists of 2 buttons. My goal is to display only the button for the other page and disable the button for the current page. Currently, when I navigate to the settings page, the settings button is hidden. However, whe ...

Having trouble debugging a Windows service? Learn how to "attach to process" and troubleshoot effectively

According to Microsoft's guidelines To begin debugging in Visual Studio, select Attach to Process from the Debug menu. A dialog box named Processes will pop up. Look for and click on the option that says Show system processes. In the section label ...

``Can you provide guidance on excluding matching values from a dictionary object in a Angular project?

I've developed a function that takes a dictionary object and matches an array as shown below: const dict = { CheckAStatus: "PASS", CheckAHeading: "", CheckADetail: "", CheckBStatus: "FAIL", CheckBHeading: "Heading1", CheckCStatus: "FAIL", ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

Is it only possible to exit early in C# using exceptions and return statements?

Just wondering, if I have the code snippet below, can I expect that either Foo() or Bar() will be executed? try { ... // No return statement here Foo(); } catch (Exception e) { Bar(); } I am well acquainted with using finally blocks, so no nee ...

Tips for fixing: "Object may be null" error in Angular routing

Currently, I am working on the angular heroes tutorial provided in the angular documentation and encountering an error. An issue has been detected, which states that the object is possibly 'null'. getHero(): void { const id = +this.route.snaps ...