我尝试在paper.js和typescript之间进行交互。
所以我想把一些事件处理程序写入PenTool
的约束器。
(因为我想使用DI并在工具创建时定义所有纸质事件)
我有下一段代码:
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);
}
}
}
}
paperService
给我纸张变量,创建新的paperScope等。
问题是我无法访问类属性到事件的功能。
我做错了什么? 提前谢谢。
答案 0 :(得分:1)
使用箭头功能来保持相同的上下文。
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帖子提供了有关此在javascript中如何运作的更多信息。