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?

>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);
    }
}

Leave a Reply