Chuyển đến nội dung

Bài 5 · Getting Started

Core Concepts of Ember Octane

Get the mental model of modern Ember - routes, templates, components, services, tracked state, arguments and actions - and see how auto-tracking updates only what changed.

You have installed Ember, created pages and reviewed the JavaScript behind it. Before going deeper into routing, components and data, it helps to hold a single picture of how the parts relate. This lesson gives you that picture, defines the vocabulary used everywhere in the Ember community, and finishes with a small working stand-in of the most important mechanism: auto-tracking.

The vocabulary

The building blocks

Router URL to route
Route Loads the model
Template What the user sees
Component Reusable UI piece

Four pieces explain most screens.

1 / 3

Here is each one in a sentence, and where you will study it:

  • Router and routes: the URL decides which routes are active; each route may load a model and guard access. See Router Basics.
  • Templates: markup with {{ }} expressions, written in .gjs/.gts files (template tag) or .hbs files. See Templates and Handlebars.
  • Components: classes plus a template, the unit of reuse. See Components.
  • Helpers and modifiers: small functions you call in templates ({{concat ...}}) or attach to elements ({{on "click" ...}}). See Helpers and Modifiers.
  • Models and the store: Ember Data describes records and caches what the API returns. See Ember Data.
  • Services: long-lived objects shared by the whole app, such as a session or notifications. The Services chapter of this track covers them.

Two kinds of values: arguments and state

Inside a component template you will use two prefixes constantly:

JavaScript
<template>
  <p>Hello, {{@name}}!</p>          {{! @name is an argument from the parent }}
  <p>Clicks: {{this.count}}</p>     {{! this.count is the component's own state }}
</template>
  • @name is an argument. The parent passed it in with <Greeting @name="Ada" />. It is read-only for the child.
  • this.count is a property of the component class. If it is marked @tracked, changing it updates the page.

The prefix tells you at a glance who owns the value. When you see @, someone else owns it; when you see this., the component does.

Tracked state and auto-tracking

Older versions of Ember made you tell the framework which values depended on which (computed properties with dependency keys) and update values with this.set(...). Octane replaced that with auto-tracking:

  1. You mark state fields with @tracked.
  2. When a template reads a tracked value, Ember remembers that this part of the page depends on it.
  3. When you assign a new value, Ember re-renders only the parts that read it.

You never list dependencies by hand, and plain getters work as derived values:

JavaScript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';

export default class Cart extends Component {
  @tracked items = [{ price: 5 }, { price: 7 }];

  get total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }

  <template>Total: {{this.total}}</template>
}

total is just a getter. Because it reads this.items, which is tracked, the template using this.total updates automatically when items is reassigned.

Tracking sees assignments. this.items = [...this.items, newItem] updates the page; this.items.push(newItem) on a plain array does not, because nothing was reassigned. The Tracked State chapter shows tools for mutable collections.

The following stand-in builds a miniature auto-tracking system in about forty lines. A cell is a tracked value. While a function runs inside autorun, every cell it reads registers that function as a dependent. Change a cell and only the dependents re-run. Real Ember is far more refined, but the principle is the same.

JS A miniature auto-tracking system

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

No output.

Notice the output: changing clicks re-runs only the "Clicks part". Changing the first name re-runs only the "Name part". Setting a cell to the value it already has does nothing. That is the efficiency you get without writing dependency lists.

A getter as derived state

Let us extend the stand-in with a derived value. A function that reads cells is automatically up to date when run again, just like a getter.

JS Derived values from cells

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

No output.

The life of a page, end to end

sequenceDiagram
  participant U as User
  participant R as Router
  participant Rt as Route
  participant T as Template
  participant C as Component
  U->>R: Visit /posts/42
  R->>Rt: model({ post_id: 42 })
  Rt-->>R: promise resolves with post
  R->>T: render with @model
  T->>C: <PostCard @post={{@model}} />
  U->>C: clicks Like
  C->>C: action updates tracked state
  C-->>T: only changed parts re-render

A visit, a model, a render, and a user action that updates tracked state.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. In a component template, what does {{@title}} refer to?

    Names starting with @ are arguments. The component's own properties are accessed with this.
  2. 2. What does @tracked do?

    Reading a tracked field during rendering records a dependency; assigning a new value invalidates those dependents.
  3. 3. Why might this.items.push(x) fail to update the page for a plain tracked array?

    Use this.items = [...this.items, x], or a tracked collection utility, so a change is recorded.
  4. 4. What is a getter such as get total() used for in a component?

    A getter recomputes whenever it is read; if it reads tracked fields, templates using it update when those change.
  5. 5. Which pair describes "data down, actions up"?

    A parent owns state and passes values and action functions as arguments. The child calls the action to request a change.

Summary

  • An Ember page is a router, routes, templates and components, supported by services, helpers, modifiers and models.
  • @name is an argument from the parent; this.name is the component's own property.
  • @tracked plus auto-tracking means you never list dependencies; reassigning a tracked field updates only what read it.
  • Getters give derived values; prefer reassigning over mutating.

Next: Router Basics

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ị.