I just can't seem to figure out what's missing here. Running the following code gives me this error:
Uncaught TypeError: Cannot read property 'addEventListener' of undefined"
class Editor{
public context: CanvasRenderingContext2D;
constructor( public canvas: HTMLCanvasElement){
this.context = this.canvas.getContext("2d");
this.canvas.addEventListener("mousedown", this.handleMouseDown);
}
handleMouseDown(ev: MouseEvent){
this.canvas.addEventListener("mousemove", this.handleMouseMove);
}
handleMouseMove(ev: MouseEvent){
console.log(ev);
console.log(ev.target);
}
}
let mapEditor = new Editor(<HTMLCanvasElement>document.getElementById("map-editor"));
But when I try a different approach, it works fine:
let cnv = document.getElementById("map-editor") as HTMLCanvasElement;
cnv.addEventListener("mousedown", handleMouseDown);
function handleMouseDown(ev: MouseEvent){
ev.target.addEventListener("mousemove", handleMouseMove);
handleMouseMove(ev);
};
function handleMouseMove(ev: MouseEvent){
console.log(ev);
console.log(ev.target);
};
I've rearranged things and searched for solutions, but the event still won't trigger. Am I overlooking something important in the language?
Edit: After some digging, I believe that the "this" keyword loses its reference to the class instance when the mousedown event is triggered, causing this.canvas to be undefined. I plan to explore alternative ways of binding methods with events.
For further explanation, check out this link: 'this'-in-TypeScript