Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 39 ยท Components and Helpers

Actions, Events and Forms

Handle clicks, input and submit events in Ember with the on modifier, the action decorator and the fn helper, and learn how child components send actions up.

A page that only displays data is a document. A page that reacts to the person using it is an application. In Ember, reacting means actions: plain JavaScript functions that you connect to DOM events and that change tracked state. Because the template re-renders when tracked state changes, you almost never touch the DOM yourself.

Real versus stand-in. Template code ({{on "click" ...}}, @action) is real Ember code shown read-only. The runnable blocks are plain JavaScript stand-ins that model the same ideas: functions bound to events, partial application and "data down, actions up".

The on modifier

You attach an event listener to an element with the {{on}} modifier. It takes the event name and a function:

JavaScript
// app/components/like-button.gjs
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { on } from '@ember/modifier';

export default class LikeButton extends Component {
  @tracked count = 0;

  like = () => {
    this.count++;
  };

  <template>
    <button type="button" {{on "click" this.like}}>
      Likes: {{this.count}}
    </button>
  </template>
}

on adds the listener when the element appears and removes it when the element goes away, so you never leak listeners. Any DOM event works: click, input, change, submit, keydown, focus, mouseenter. You can attach several on modifiers to one element, and pass options such as {{on "scroll" this.handler passive=true}}.

The handler receives the native event object as its first argument:

JavaScript
handleKey = (event) => {
  if (event.key === 'Escape') {
    this.close();
  }
};

@action versus arrow functions

A method used as an event handler loses its this (see Modern JavaScript You Need for Ember). Two fixes are common:

JavaScript
import { action } from '@ember/object';

export default class Counter extends Component {
  @tracked count = 0;

  // 1. the decorator binds the method to the instance
  @action
  increment() {
    this.count++;
  }

  // 2. an arrow function field is already bound
  decrement = () => {
    this.count--;
  };
}

Both work. @action has the advantage that the method stays on the prototype (easier to stub in tests and shared by all instances); arrow fields are simple and need no import. Choose one style per project and stay consistent.

Passing arguments with fn

Often a handler needs to know which item was clicked. The {{fn}} helper creates a new function with some arguments already filled in (partial application):

JavaScript
import { fn } from '@ember/helper';

<template>
  <ul>
    {{#each @items as |item|}}
      <li>
        {{item.name}}
        <button type="button" {{on "click" (fn this.remove item)}}>Remove</button>
      </li>
    {{/each}}
  </ul>
</template>

When the button is clicked, this.remove is called with item first, then with the event: remove(item, event). You never write inline code in a template; you always pass a function value.

JS fn is partial application

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Forms: input, change and submit

Ember does not hide the browser's form behavior. You read values from the event:

JavaScript
export default class SearchBox extends Component {
  @tracked query = '';

  updateQuery = (event) => {
    this.query = event.target.value;
  };

  search = (event) => {
    event.preventDefault();
    this.args.onSearch(this.query);
  };

  <template>
    <form {{on "submit" this.search}}>
      <label>
        Search
        <input type="search" value={{this.query}} {{on "input" this.updateQuery}} />
      </label>
      <button type="submit">Go</button>
    </form>
  </template>
}

Notes:

  • value={{this.query}} sets the initial and updated value of the input property. Together with the input handler this is a controlled input: the tracked field and the screen stay in sync.
  • Call event.preventDefault() on submit, or the browser reloads the page.
  • Ember also ships the <Input> and <Textarea> built-in components, which two-way bind with @value. Many teams prefer plain elements plus {{on}} because the data flow is explicit. See Forms and Inputs.
  • Use event.target.checked for checkboxes and event.target.value for selects.

Data down, actions up

Parents give a child its data as arguments. The child cannot change them (arguments are read-only), so it calls a function the parent passed and the parent decides what to do:

JavaScript
// app/components/todo-form.gjs (the class has: submit() { this.args.onAdd(this.title); })
<template>
  <form {{on "submit" this.submit}}>
    <input value={{this.title}} {{on "input" this.setTitle}} />
    <button>Add</button>
  </form>
</template>

// app/templates/todos.gjs
<template>
  <TodoForm @onAdd={{this.addTodo}} />
</template>
flowchart TD
  P["Parent: owns the list"] -- "@todos (data down)" --> C["TodoList"]
  P -- "@onAdd (function down)" --> F["TodoForm"]
  F -- "calls onAdd(title) (action up)" --> P

The parent owns the state. The form only reports what the user typed.

This one-way flow means you can always find who changes a piece of state: the component or controller that owns it.

JS Data down, actions up

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Preventing and stopping events

Sometimes the default needs cancelling. Common cases:

  • event.preventDefault(): stops a form submit or link navigation.
  • event.stopPropagation(): keeps a click from reaching a parent's handler.
  • {{on "click" this.handler once=true}}: runs once, then removes itself.

The on modifier also accepts capture=true and passive=true, the same options as addEventListener.

Actions on routes and controllers

Controllers can have actions too, with the same @action decorator, and route templates can use {{on}} the same way. Route-level actions (like error and willTransition) exist but are used rarely; prefer a service or a controller action that calls this.router.transitionTo(...) (see Links, Navigation and the Router Service).

Common mistakes

  • Calling the function in the template. {{on "click" this.like}} passes the function. this.like() is not valid template syntax.
  • Forgetting preventDefault on submit. The page reloads and state is lost.
  • Mutating an argument. this.args.todos.push(x) may seem to work, but it breaks the data-down rule; ask the parent through an action.
  • Using a plain method without @action. this is undefined when the browser calls it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which template syntax attaches a click handler?

    The on modifier takes the event name and a function and cleans the listener up automatically.
  2. 2. What does (fn this.remove item) produce?

    fn does partial application, so the handler is called later, with item first and the event after it.
  3. 3. Why is @action (or an arrow field) needed on a handler method?

    A plain method loses its this when called as an event handler. @action binds it to the instance.
  4. 4. A child component needs to change data owned by its parent. What should it do?

    Arguments are read-only. The parent passes a function (an action) and decides how to update its own state.

Summary

  • Attach events with {{on "event" handler}}; the listener is cleaned up for you.
  • Bind methods with @action, or use arrow function fields.
  • (fn handler arg) presets arguments, so one handler serves many rows.
  • Read form values from event.target, and call preventDefault() on submit.
  • Data flows down as arguments, actions flow up as functions.

Next: Helpers and Modifiers