Search code examples
javascriptangulartypescriptfabricjsngoninit

Passing Value to Functions From ngOnInit


I have a button that calls clip function. I need to pass values from ngOnInit to that function but i can't. I get undefined error for (for example) this.firstX. How can i pass values from ngOnInit to functions?

export class AppAppComponent implements OnInit {

  public firstX: number;
  public firstY: number;
  public lastX: number;
  public lastY: number;

  constructor(mdIconRegistry: MdIconRegistry) {
    mdIconRegistry
      .registerFontClassAlias('fontawesome', 'fa');
  }

  ngOnInit() {

    let canvas = new fabric.Canvas('cLeft');
    let src = "../../images/kupurSecond.jpg";

    canvas.on('mouse:down', function (event) {
      var position = canvas.getPointer(event.e);
      this.firstX = position.x;
      this.firstY = position.y;
    });

    canvas.on('mouse:up', function (event) {
      var position = canvas.getPointer(event.e);
      this.lastX = position.x;
      this.lastY = position.y;
      // ReLoading Image
      loadImage(src, canvas, this.firstX, this.firstY, this.lastX, this.lastY);
    });

    loadImage(src, canvas);

  }; 

  public clip() {
    console.log(this.firstX);
  }

}

Solution

  • You have to use the arrow notation to remain the same this context.

    canvas.on('mouse:down', (event) => {
          var position = canvas.getPointer(event.e);
          this.firstX = position.x;
          this.firstY = position.y;
    });
    

    Same goes for the mouse:up function. Just never use the word function in typescript, and you are golden