Preferred way to wire up actions?

I’ve noticed in most Ember applications I work on there seems to be two common ways of wiring up actions.

Action 1: onclick
<button onclick={{action "myAction1"}}> Action 1 </a>

… and …

Action 2: action in element space
<button {{action "myAction2"}}> Action 2 </a>

From what I can tell, the difference between these two buttons is that Action 1 is a little more low level. It will not prevent the default browser event and when it invokes myAction1 it will pass the event as an argument. Action 1 also has the perceived benefit of being more in line with “just html and js”

Action 2 on the other hand prevents the default browser behavior and does not give the developer access to the event.

I’m wondering if there are any best practices here for when to use each style of action?

I’m thinking that the onclick style should be used when you need access to the event or want the default browser behavior. This makes senses in when working with actions attached to elements like select dropdowns, because you would want the event to get the selected option. See this excellent blog post by @balint

And {{action}} in element space makes sense for things like buttons, where you want a click to trigger an action, but don’t need to be concerned with the event or browser default. The guides use this style of {{action}} in element space for wiring up a button.

So how does that sound… What am I missing? When do you use onclick vs {{action}} in element space?

3 Likes

I’ve only been using native actions (the onclick style) for a while now and didn’t see the need for the element space one. I call event.preventDefault() if I need to (when submitting a form, for example).

2 Likes

Marie’s emberconf talk does an excellent job covering the differences.

I’m torn between the two. While I really like the event delegation system used by the element modifier syntax(<button {{action ...}}>), I usually want access to the native event, which is accessible only with the html attribute syntax (<button onclick={{action ...}}>).

One big roadblock (for me) with html attribute syntax is that onfocusin and onfocusout attributes do not exist, so if you want event bubbling you’re forced to use the element modifier syntax. (Because under the hood it’s using appRoot.addEventListener('focusin').)

2 Likes

I found this article to be helpful, and would generally lean towards using onclick only when I need the low-level stuff (see article).