Explaining the various ways to make actions and call them to a newcomer


#1

Hi, I’m having difficulties explaining the subtleties behind Ember’s actions API(s?). Between

  • {{my-component myAction="anAction"}}
  • {{my-component myAction=(action "anAction")}}

the difference is fairly simple: “Use the second form as it allows for better control” (return value, etc…).

But add to that the component’s syntax, with either:

  • this.attrs.anAction() (which looks like an incidental feature)
  • this.get('anAction')() (which is ugly)
  • this.sendAction('anAction') (which does not benefit from closure actions goodness)

It’s very hard to give to newcomers a clear mental model of what they should do and how they should do it.

Add up that:

and you are in for a very confusing training session.

So, I wanted to ask if there were established best practices (beyond https://guides.emberjs.com/v2.14.0/components/triggering-changes-with-actions/) and/or a definitive guide and/or a definitive addon.

If someone had an addon as useful to the actions as ember-native-dom-helpers is useful to testing, I’d be eternally (yes, eternally!) grateful!

All the best to you all, dear Embereñas y Embereños!


#2

Hi there, you are correct that the best practices are as listed on that guides page.

Therefore, most of the time, you will just want to do:

{{my-component myAction=(action "anAction")}} And this.get('anAction')()

this.attrs.anAction() is an incidental feature, I wouldn’t advise relying on that.

this.sendAction('anAction') is essentially a holdover from the old way of doing it. You can use it if you want to use string actions, or if the action may or may not be passed. You don’t get a return value, but you do get bubbling from controllers to their parent routes if you’re passing in the action from a controller. Most of the time, it’s probably best to avoid it.

In short, the definitive best practice is to do as the guides to suggest.