How do I make sure that a function is not undefined in typescript?

443 views Asked by At

I'm sorry for the terrible title, but I have the following situation: I'm using angular with Knova node package to create a webapp for my thesis work to finish Uni.

I have two components on one of my pages: the first one being a navbar, and the second the edior itself. I have a button in the navbar, that I add an eventlistner to in my EditorComponent class, so when I click it, I can initiate the importOwnSave method to import shapes from an xml file. I tell you all this to make the situation more clear.

So the heart of my problem is, that I have a method:

addTransformerListeners(shape: Shape): void {
const component = this;
this.stage.on('click', function (e) {
  e.evt.preventDefault();
  if (!this.clickStartShape) {
    return;
  }
  if (e.target._id == this.clickStartShape._id) {
     {...}
  }
  else {
     {...}
  }
});
}

which when called from another method, at the end of my file, but in the same class (class EditorComponent) breaks:

importOwnSave(): void {    

    var component = this;

    {... variable value settings, I'm 100% sure this is nothing important ...}

    var addTransformers = this.addTransformerListeners; //<- this becomes undefined

    console.log(addTransformers, this.addTransformerListeners);

    {...}
}
    

the console log shows that addTransformers and this.addTransformerListeners are undefined, and anywhere I try to call that method it's undefined, and throws an error:

ERROR TypeError: this.addTransformerListeners is not a function
    at HTMLButtonElement.importOwnSave (editor.component.ts:929)

The good part about this is that in another method, used to generate a rectangle to the canvas, invokes the method just fine:

addRectangle(): Rect {
    const rectangle = this.shapeService.rectangle();
    this.shapes.push(rectangle);
    this.layer.add(rectangle);
    this.addTransformerListeners(rectangle); //<-
    return rectangle;
}

when addRectangle is called, this.addTransformer has the correct value of ƒ addTransformerListeners(shape), and runs as intended

I'm really sorry to bother you, reading this with my stupid code, but I'm stuck on so many levels I can not even describe, and after searching a lot, nobody seems to have had quite the same issue. If you are considering wirting an answer, know that everything might help, even the things you would consider as a basic element of working in typescript, I could have easily missed something important, as I'm not quite the professional using angular and TS. Thank you for reading!

0

There are 0 answers