1

I would like to know how to access and modify the variable a in anonymous functions, i try to put arrow but i get in my browser: undefined

 import * as Konva from 'konva';

export class classTest {

    public a: number;

    access(){ 

        var stage = new Konva.Stage({ container: 'container', width: 400, height: 250 });

        var layer1 = new Konva.Layer();
        var imageObj = new Image();
        var self = this
        imageObj.onload = function () {

            self.a = 150

            var yoda = new Konva.Image({
                x: 50,
                y: 50,
                image: imageObj,
                width: 106,
                height: 118
            });
            layer1.add(yoda);
            //stage.add(layer1)

        };
        imageObj.src = '/assets/images/yoda.jpg';
        //console.log(a)

If i add in layer1 a rect with width = a it's going to be the same thing as you explained ( i get a line) so how can I do it.

        var box = new Konva.Rect({
            x: 20, y: 20,
            width: this.a, 
            height: 50,
            fill: '#00D2FF', stroke: 'black',
            strokeWidth: 4
       });

       stage.add(layer1)
    }
problème0123
  • 841
  • 2
  • 9
  • 23
  • I downvoted because your code sample is buggy and cannot actually work as persented, so any advice given has to make assumptions - and we all know what that means ;-) – Vanquished Wombat Nov 04 '18 at 21:16
  • But, in the interests of moving things along...is this not a standard scoping issue? You define stage as a local var in function createElements() . Konvajs Stage is a 'helper' rather than a 'wrapper' for the html canvas element meaning that the canvas element stays in the DOM and visible to the user even though the variable pointing to the Konvajs Stage object has gone to garbage collection. When you refer to 'this.stage' in the event handler some time later, it is no surprise that an error occurs. Actually the 'this' prefix is very suspect here anyway. Clean up the code for a better answer. – Vanquished Wombat Nov 04 '18 at 21:19
  • Hello, thank for your reply, I changed my code and explain better my problem. – problème0123 Nov 05 '18 at 07:16

1 Answers1

0

console.log(this.a);

is executed earlier than

imageObj.onload

That's why you get undefined

Inside imageObj.onload everything is working right.

ZeroCho
  • 1,358
  • 10
  • 23