打字稿 Konva 类变量不在范围内



我有一个Ionic项目,我正在尝试使用Konva.js。我遇到的问题是我的一个类方法在内部函数中没有被识别。一旦用户单击文本块(tossUpText(,我正在尝试调用一个函数,但是我目前收到一个错误(在代码中指出(,因为该函数显示为未定义。

这是错误的截图:https://i.stack.imgur.com/EWpwx.png。

做了更多的分析,我发现在这个范围内,this是 https://i.stack.imgur.com/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();
    }
  }
}

使用箭头函数保存this引用:

this.tossUpText.on('mouseup touchend', () => {
  this.startTossUpTimer(); // error here
});

最新更新