Tracked properties introduce a simpler, ergonomic system for tracking state changes in Ember applications. Leveraging new JavaScript functions, tracked properties allow Ember to write more intuitive and error-free code while reducing the surface area of the API.
Tracked properties are imported from @glimmer/tracking
and used as a decorator to mark the tracked properties. If the property is marked for tracking, the DOM will be re-rendered each time the value of the tracked property changes. Hence, tracked properties are a fundamental change in how Ember handles the state.
Decorator notation (@
) is used to annotate and mark the values or properties as tracked:
@tracked property-name
No parameters are required to be passed in.
There is no return value. When a property is marked as tracked, the DOM will be re-rendered each time the value of that tracked property changes.
The code snippet below shows how we can annotate and mark properties as tracked.
Note: The piece code provided in the below widget is not the complete application’s code. Only necessary files are shown.
In this example, we marked evenNumber
as a tracked property. Now whenever the evenNumber
changes, the DOM will be re-rendered.
Note: Please hit the
Run
button and to open the application inside a new tab, click on the link provided next to the line “Your app can be found at:”.
import Controller from '@ember/controller'; import {action} from '@ember/object' import { tracked } from '@glimmer/tracking'; export default class ApplicationController extends Controller { @tracked evenNumber = 2; @action nextEvenNumber(){ this.evenNumber = this.evenNumber + 2; } @action previousEvenNumber(){ this.evenNumber = this.evenNumber - 2; } }
In application.js
:
Lines 1-3: We imported the required libraries.
Line 6: We marked the evenNumber
property as tracked using the @tracked
decorator. By default, the value of evenNumber
is 2
. Now whenever the value of evenNumber
will change, the DOM will be re-rendered.
Lines 8-15: We created two event handlers that will increment and decrement the value of evenNumber
by 2
respectively.
In application.hbs
:
Line 1: We set the page title.
Line 3: We added the evenNumber
property in an h1
tag. We use this
to refer to the properties from controllers.
Line 6: We created a button and added our nextEvenNumber
event handler. Whenever the user clicks this button, the value of evenNumber
will be incremented by 2
and the DOM will be re-rendered.
Line 7: We created a button and added our previousEvenNumber
event handler. Whenever the user clicks this button, the value of evenNumber
will be decremented by 2
and the DOM will be re-rendered.
RELATED TAGS
View all Courses