Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue with using this inside afterLoad static method #652

Closed
lb- opened this issue Feb 8, 2023 · 2 comments · Fixed by #658
Closed

Issue with using this inside afterLoad static method #652

lb- opened this issue Feb 8, 2023 · 2 comments · Fixed by #658

Comments

@lb-
Copy link
Contributor

lb- commented Feb 8, 2023

Problem

The afterLoad method is confusingly not called with a this context of the controller constructor but is instead undefined.

TypeScript is advising that this will be the controller constructor but at runtime it is failing.

Steps to reproduce

Create a controller

export class LoaderController extends Controller {
  static values = {
    durationSeconds: { type: Number, default: 30 },
  };

  static afterLoad(identifier: string, application: Application) {
    const { controllerAttribute } = application.schema;
    console.log('afterLoad test', this); // this is undefined
    console.log('afterLoad stuff', {identifier, controllerAttribute });
    console.assert(this.values.durationSeconds.default, 30); // errors as this is undefined
  }
}

Expect that the this will be the controller constructor. Instead it is undefined.

Potential solution

const afterLoad = (definition.controllerConstructor as any).afterLoad

 const afterLoad = (definition.controllerConstructor as any).afterLoad?.bind(controllerConstructor)
lb- pushed a commit to lb-/stimulus that referenced this issue Feb 13, 2023
marcoroth pushed a commit that referenced this issue Feb 13, 2023
- Fixes #652

Co-authored-by: LB Johnston <lb.johnston@virginaustralia.com>
@ippeiukai
Copy link

bitten by this bug. hope to have a patch release.

@marcoroth
Copy link
Member

@ippeiukai this fix is shipping in the next release.

If you don't want to wait you can use the latest dev-build from main using:

yarn add @hotwired/stimulus@https://github.com/hotwired/dev-builds/archive/refs/tags/@hotwired/stimulus/eda0f9d.tar.gz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging a pull request may close this issue.

3 participants