Chuyển đến nội dung

Bài 13 · Components and Helpers

Helpers and Modifiers

Learn Ember's built-in helpers (if, each, let, concat, get, array, hash) and how to write your own helper and element modifier, with runnable JavaScript stand-ins.

Templates in Ember are deliberately limited: no arbitrary JavaScript, no loops written by hand. When a template needs a little logic, it calls a helper, a function used inside {{ }}. When it needs to do something to a DOM element (focus it, measure it, attach a third-party library), it uses a modifier, a function attached to an element in curly braces. This lesson covers the built-ins and then shows how to write both kinds yourself.

Real versus stand-in. The .gjs snippets are real Ember code, read-only here. The runnable blocks reimplement the ideas (a helper is a function, a modifier is a function with set-up and clean-up) in plain JavaScript.

Built-in helpers you will use every day

Helpers are called with subexpression syntax inside a mustache. The first word is the helper; the rest are arguments. Nest them in parentheses:

JavaScript
import { concat, array, hash, get, fn } from '@ember/helper';

<template>
  {{concat "Hello, " @user.name "!"}}

  {{#each (array "red" "green" "blue") as |color|}}
    <li>{{color}}</li>
  {{/each}}

  <Profile @options={{hash theme="dark" compact=true}} />

  {{get @scores @playerId}}
</template>
Helper What it does
concat Joins values into one string.
array Builds an array inline.
hash Builds an object inline (named arguments become keys).
get Reads a property by dynamic key, like scores[playerId].
fn Partially applies a function (see Actions, Events and Forms).
on A modifier: adds an event listener.
unique-id Returns a unique string for linking labels and inputs.
log Prints its arguments to the console, handy for debugging.

Many more come from add-ons such as ember-truth-helpers (eq, not, and, or, gt) or ember-composable-helpers (sort-by, take, join). Check what your app has installed in package.json before you assume a helper exists.

Control flow: if, each, let, in-element

Strictly speaking these are keywords written as blocks, not helpers, but you use them the same way:

JavaScript
<template>
  {{#if @user.isAdmin}}
    <AdminBar />
  {{else if @user.isMember}}
    <MemberBar />
  {{else}}
    <LoginPrompt />
  {{/if}}

  {{#each @posts key="id" as |post index|}}
    <PostCard @post={{post}} @position={{index}} />
  {{else}}
    <p>No posts yet.</p>
  {{/each}}

  {{#let (concat @first " " @last) as |fullName|}}
    <h1>{{fullName}}</h1>
  {{/let}}
</template>
  • if is falsy for false, null, undefined, 0, '', NaN and (unlike JavaScript) an empty array.
  • each can take key="id" so Ember reuses DOM when a list is reordered; {{else}} runs for an empty list.
  • let names a value once so you do not repeat a long expression.
  • Inline if works as a ternary: class={{if this.isOpen "open" "closed"}}.
JS Stand-in: helpers are plain functions

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

No output.

Writing your own helper

When no built-in fits, write a function helper. In modern Ember (4.5+) any plain function is a helper if it is imported and used in a template:

JavaScript
// app/helpers/format-price.js
export function formatPrice(cents, currency = 'USD') {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}
JavaScript
// app/components/price.gjs
import { formatPrice } from '../helpers/format-price';

<template>
  <span class="price">{{formatPrice @cents}}</span>
  <span>{{formatPrice @cents "EUR"}}</span>
</template>

Rules for helpers:

  • They must be pure: the same inputs give the same output, with no side effects. The renderer may call them again whenever an input changes.
  • Positional arguments arrive as function arguments. Named arguments (currency="EUR") arrive as an object, so for those write formatPrice(cents, { currency }) or use the class-based Helper with compute(positional, named).
  • Return a string, a number, a boolean or an object, never HTML. Output is escaped, which is a security feature.

For helpers that need services (like a translation helper), use a class helper:

JavaScript
import Helper from '@ember/component/helper';
import { service } from '@ember/service';

export default class TranslateHelper extends Helper {
  @service intl;

  compute([key], named) {
    return this.intl.t(key, named);
  }
}
JS A price helper

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

No output.

Modifiers: working with elements

A modifier runs code with access to the DOM element it is attached to. Use one when you need the real element: autofocus, scroll into view, a tooltip library, a resize observer, a chart.

JavaScript
// app/modifiers/autofocus.js
import { modifier } from 'ember-modifier';

export default modifier((element) => {
  element.focus();
});
JavaScript
import autofocus from '../modifiers/autofocus';

<template>
  <input type="text" {{autofocus}} />
</template>

modifier comes from the ember-modifier package, which is installed in new apps. A modifier can return a cleanup function, called before it re-runs and when the element is removed:

JavaScript
export default modifier((element, [message], { delay = 0 }) => {
  const id = setTimeout(() => (element.textContent = message), delay);
  return () => clearTimeout(id); // cleanup
});

Positional arguments ([message]) and named arguments ({ delay }) are passed in. Any tracked value the modifier reads while it runs is automatically watched: when one changes, the cleanup runs and the modifier runs again.

JS Stand-in: a modifier with cleanup

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

No output.

Helper or modifier or component?

  • Helper: computes a value for the template. No DOM access, no state.
  • Modifier: does something to an element (and undoes it).
  • Component: renders markup and can hold state.

If you are tempted to use a modifier to produce text, you probably want a helper or a getter. If you need document.querySelector, you probably need a modifier, so you get the element directly instead.

flowchart LR
  V["Value for display?"] -- yes --> H["Helper or getter"]
  V -- no --> E["Need the DOM element?"]
  E -- yes --> M["Modifier"]
  E -- no --> C["Component (markup and state)"]

A quick chooser.

Common mistakes

  • Side effects in a helper. Do not fetch data or write to state in a helper; it can run many times.
  • Assuming a helper exists. eq and not are not built in; install the add-on or use a getter.
  • Forgetting the cleanup in a modifier. A listener or timer left behind leaks memory.
  • Reading the DOM in a component constructor. The element does not exist yet; use a modifier.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which statement about helpers is correct?

    Helpers compute values from inputs and can be re-run at any time, so side effects do not belong in them. Their output is escaped, not treated as HTML.
  2. 2. What is a modifier for?

    Modifiers are the place for element-level work such as focus, observers or third-party widgets.
  3. 3. In an Ember template, is an empty array truthy in {{if}}?

    Ember's if treats empty arrays as falsy, which is convenient for lists but different from plain JavaScript.
  4. 4. How does a modifier undo what it did?

    The function returned from the modifier runs before re-running and when the element is removed.

Summary

  • Helpers are pure functions called in templates; the built-ins include concat, array, hash, get, fn and unique-id.
  • if, each and let are block keywords; each supports key and {{else}}.
  • Any imported plain function can act as a helper; class helpers can use services.
  • Modifiers attach behavior to elements with automatic cleanup and re-running when tracked arguments change.
  • Choose helper for values, modifier for DOM work, component for markup and state.

Next: Component Patterns: Yield, Blocks and Attributes

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.