1

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.

pavel
  • 1,736
  • 1
  • 14
  • 23
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Andreas May 04 '17 at 13:03

1 Answers1

1

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.

Community
  • 1
  • 1
toskv
  • 30,680
  • 7
  • 72
  • 74