Effect observation
Aurelia provides a higher-level API for simplifying some common tasks to handle a common reactivity intent in any application: run a function again when any of its dependencies have been changed.
This function is called an effect, and the dependencies are typically(1) tracked when they are accessed (read) inside this effect function. The builtin @observable
decorator from Aurelia enables this track-on-read capability by default.
Aurelia provides a few ways to declare a dependency for an effect function. The most common one is the track "on read" of a reactive property.
In the following example:
The property coord
of a MouseTracker
instance will be turned into a reactive property and is also aware of effect function dependency tracking.
Creating an Effect
The effect API is provided via the default implementation of an interface named IObservation
.
An example to retrieve an instance of this interface is per following:
Getting from a container directly
Getting through injection
Autoinjection (if you are using TypeScript)
After getting ahold of an IObservation
instance, an effect can be created via the method run
of it:
Note that the effect function will be run immediately.
By default, an effect is independent of any application lifecycle, which means it does not stop when the application that owns the observation
instance has stopped. To stop/destroy an effect, call the method stop()
on the effect object:
Effect Observation & Reaction Examples
Creating an effect that logs the user mouse movement on the document
Now whenever the user moves the mouse around, a log will be added to the console with the coordinate of the mouse.
Creating an effect that sends a request whenever user focus/unfocus the browser tab
Last updated
Was this helpful?