I have an Ionic project that I am trying to use Konva.js on. The problem I am having is that one of my class methods is not being recognized in an inner function. I am trying to call a function once the user clicks a block of text (tossUpText), but I am currently getting an error (pointed out in the code) as the function appears as not defined.
Here is a snip of the error: https://i.sstatic.net/EWpwx.png.
I did some more analysis and I found that in that scope, this
is https://i.sstatic.net/paFFV.png.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as Konva from 'konva';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tossUpState: string = 'NOT_STARTED';
stage: Konva.Stage;
public layer: Konva.Layer;
public tossUpText: Konva.Text;
constructor(public navCtrl: NavController) {
}
ngAfterViewInit() {
var width = window.innerWidth;
var height = window.innerHeight;
this.stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
this.layer = new Konva.Layer();
this.tossUpText = new Konva.Text({
x: this.stage.getWidth() / 2 - 100,
y: 15,
text: '5.00',
fontSize: 100,
fill: 'green'
});
this.tossUpText.align('center');
// add the shape to the layer
this.layer.add(this.tossUpText);
// add the layer to the stage
this.stage.add(this.layer);
this.tossUpText.on('mouseup touchend', function(){
this.startTossUpTimer(); // error here
});
}
startTossUpTimer() {
console.log(this);
if (this.tossUpState == 'NOT_STARTED') {
// this.setTossUpTime();
}
}
}
Use arrow function to save this
reference:
this.tossUpText.on('mouseup touchend', () => {
this.startTossUpTimer(); // error here
});