Search code examples
.nettypescriptpaperjs

"This" keyword in paper.js event into constractor


I tried to do interaction between paper.js and typescript.

So I want to write some event handlers into constractor of PenTool. (because I want to use DI and define all paper-events while tool is creating)

I have next wrap of code:

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 give me paper variable, create new paperScope etc. The problem is I can't get access to class properties into event's function.

What I do wrong? Thank in advance.


Solution

  • Use arrow functions instead to keep the same 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 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 = (event) => {
    
          console.log('pen -> mouse drag!');
    
          if (event.modifiers.shift) {
            this.path.lastSegment.point = event.point;
          } else {
            this.path.add(event.point);
          }
        }
      }
    
    }
    

    This post has a lot more information on how this works in javascript.