ember-cli-typescript
ember-cli-typescript copied to clipboard
(documentation) Closure actions
It wasn't entirely clear to me how to handle closure actions in components.
I found myself creating an empty function on my components to properly enable type hinting. Luckily @chriskrycho had a clear explanation how to handle Closure Actions in components, and this should probably be in the documentation somewhere.
Here the below scenarios:
-
If it's genuinely optional, assigning a no-op function as the default is fine. Then you can just do
this.myAction()regardless elsewhere. -
If it's not optional, I currently do something like this:
import Component from '@ember/component'; import { assert } from '@ember/debug'; import { action } from '@ember-decorators/object'; export default class myComponent extends Component { myPassedAction!: (name: string) => void; init() { super.init(); assert('`myPassedAction` is required', typeof this.myPassedAction === 'function'); } @action someAction() { this.myPassedAction("hello"); } } -
If it's optional and you want to do the check instead of always invoking with a no-op function:
import Component from '@ember/component'; import { assert } from '@ember/debug'; import { action } from '@ember-decorators/object'; export default class MyComponent extends Component { myPassedAction?: (name: string) => void; @action someAction() { if (this.myPassedAction) { this.myPassedAction("hello"); } } }
Thanks so much for writing this up! We'll try to get it integrated into the docs sometime this week!
This was superseded by the Octane programming model, where arguments are separate from the backing class properties. 🎉