ember-cli-typescript icon indicating copy to clipboard operation
ember-cli-typescript copied to clipboard

(documentation) Closure actions

Open pjcarly opened this issue 6 years ago • 1 comments

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:

  1. If it's genuinely optional, assigning a no-op function as the default is fine. Then you can just do this.myAction() regardless elsewhere.

  2. 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");
      }
    }
    
  3. 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");
        }
      }
    }
    

pjcarly avatar Mar 25 '19 13:03 pjcarly

Thanks so much for writing this up! We'll try to get it integrated into the docs sometime this week!

chriskrycho avatar Mar 25 '19 13:03 chriskrycho

This was superseded by the Octane programming model, where arguments are separate from the backing class properties. 🎉

chriskrycho avatar Sep 28 '23 22:09 chriskrycho