Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get outer this-context without loosing inner one

I need to have access to two this-contexts at the same time

export class ToolSelectionComponent implements OnInit {
  @ViewChild('toolGroupGrid') public grid: GridComponent;

  public tools: Tool[] = [...];
  public toolGroups: { Id: number, Name: string }[] = [...];
  public toolsGroupAssignments: { GroupId: number, ToolId: bigint }[] = [...];

  public childGrid: GridModel | GridComponent = {
    columns: [...],
    load() {
      const grid = this as GridComponent;
      const groupId = grid.parentDetails.parentRowData['Id'];
      grid.dataSource = outerThisAsVariable.tools.filter(t => t.groupId === groupId);
    }
  };

  ...
}

For some reason I don’t know when defining load this way this returns different values than childGrid when defining load as a callback and binding this. So I have to define load this way. But how do I get access to the outer variables at the same time?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could wrap the value in an immediately invoked function and pass the component that way, e.g.:

export class ToolSelectionComponent {
  public parentProp = 42;

  public childGrid = (component => ({
    columns: 3,
    load() {
      const grid = this;
      
      console.log(grid.columns);
      console.log(component.parentProp);
    }
  }))(this);
}

Alternatively you can move the assignment of the childGrid to the contructor, where you will also have access to the component as this and can assign it to a local variable which can be used in load().

This is actually the compiled JS of the above code (unless the flag useDefineForClassFields is turned on):

export class ToolSelectionComponent {
    constructor() {
        this.parentProp = 42;
        this.childGrid = (component => ({
            columns: 3,
            load() {
                const grid = this;
                console.log(grid.columns);
                console.log(component.parentProp);
            }
        }))(this);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading