1

If I write it like this, I can't use this keyword

  LoadDrawing(drawing_name) {
    this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name);
  }


  LoadCB(drawing, drawing_name) {
    if (drawing == null) {
     return;
    }   
    this.DrawingName = drawing_name;
    drawing.SetParentElement("glg_area");
  }

I dont know what to pass that drawing & drawing_name get same thing when pass using params

LoadDrawing(drawing_name) {
        this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB(param1,param2),drawing_name);
      }
5
  • Can you share the demo? Commented Dec 20, 2019 at 5:15
  • sorry I can't provide demo Commented Dec 20, 2019 at 5:16
  • Where is this LoadWidgetFromURL method coming from? Commented Dec 20, 2019 at 5:16
  • that is from JS library which is GLG Commented Dec 20, 2019 at 5:17
  • Well, not aware about glg but without demo I can't play the game of imagination! Good luck! Commented Dec 20, 2019 at 5:20

2 Answers 2

2

You can preserve the this binding of LoadCB by defining it as an arrow function:

LoadDrawing(drawing_name) {
    this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name);
}


LoadCB = (drawing, drawing_name) => {
    if (drawing == null) {
     return;
    }   
    this.DrawingName = drawing_name;
    drawing.SetParentElement("glg_area");
}

Note that this is nothing to do with TypeScript, but ES6 JavaScript classes.

ES6 class methods treat this bindings in the same way as a function defined using the function keyword does - in a way that is dependent on the call site rather than the lexical scope of the function. Arrow functions use lexical scope and so preserve the this binding in situations such as the above.

Sign up to request clarification or add additional context in comments.

Comments

0

Solved like this :

  LoadDrawing(drawing_name) {
        this.glg.LoadWidgetFromURL(drawing_name, null,(glg)=>this.LoadCB(glg,drawing_name),drawing_name);
      }    
      LoadCB(drawing, drawing_name) {
        if (drawing == null) {
         return;
        }   
        this.DrawingName = drawing_name;
        drawing.SetParentElement("glg_area");
      }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.