DEV Community

Michal Bryxí
Michal Bryxí

Posted on

Ember {{on}} vs {{action}} caveat

Today I learned one important difference between the traditional way of invoking actions in Ember via an action helper:

<button {{action "submit"}}>
  Click me!
</button>
Enter fullscreen mode Exit fullscreen mode

And via the new on element modifier:

<button {{on "click" this.submit}}>
  Click me!
</button>
Enter fullscreen mode Exit fullscreen mode

The subtle, yet important thing is that action helper prevents default browser action, but on element modifier does not.

Why is this important? If you'd have the buttons from the example above inside a <form> tag, then the first button will work as expected (action will be triggered), but second button will cause an unexpected full page reload on click.

Ways to fix

Two easy fixes come to my mind:

Either you can change the type of the button so that it does not trigger a submit:

<form>
  <button type="button" {{on "click" this.submit}}>
    Click me!
  </button>
</form>
Enter fullscreen mode Exit fullscreen mode

Or you can use ember-event-helpers addon.

Top comments (0)