Reputation: 2249
I started using typescript together with angularjs. I have written a simple class that is responsible for drag and drop behavior (or will be in future). But right now in my handleDragEnd function when I access canvas element I get error
Cannot read property of undefined
Below is my code - if someone could tell me what I am doing wrong I would be grateful.
class ToolBox {
private canvas;
constructor(canvas)
{
this.canvas = canvas;
$(".beacon").draggable({
helper: 'clone',
cursor: 'pointer',
start: this.handleDragStart,
stop: this.handleDragEnd
});
}
handleDragStart()
{
console.log('Drag Started!');
}
handleDragEnd()
{
var pointer = this.canvas.getPointer(event.e);
console.log('Drag End!');
return;
}
}
Upvotes: 1
Views: 1329
Reputation: 106840
Since class methods are defined on ToolBox.prototype
, the value of this
is getting lost when you pass in the methods directly.
Change:
start: this.handleDragStart,
stop: this.handleDragEnd
To:
start: () => this.handleDragStart(),
stop: () => this.handleDragEnd()
That will preserve the value of this
by calling the methods on the instance.
Upvotes: 2