Event API
The TYPO3 JavaScript Event API enables JavaScript developers to have a stable event listening interface. The API takes care of common pitfalls like event delegation and clean event unbinding.
Warning
When using import
statements, it is vital that you use the suffix
.js
to any import statements, when you are in the scope of Java
.
Only when you create your code in Type
(using .ts
suffix), you
need to omit the .js
extension in import
statements.
See https://github.com/microsoft/TypeScript/issues/16577 for the reasoning of this.
Event Binding
Each event strategy (see below) has two ways to bind a listener to an event:
Direct Binding
The event listener is bound to the element that triggers the event. This is done
by using the method bind
, which accepts any element, document
and
window
.
Example:
Event Delegation
The event listener is called if the event was triggered to any matching element inside its bound element.
Example:
import RegularEvent from '@typo3/core/event/regular-event.js';
new RegularEvent('click', function (e) {
// Do something
}).delegateTo(document, 'a[data-action="toggle"]');
The event listener is now called every time the element matching the selector
a
within document
is clicked.
Release an event
Since each event is an object instance, it is sufficient to call release
to
detach the event listener.
Example:
Event strategies
The Event API brings several strategies to handle event listeners:
RegularEvent
The Regular
attaches a simple event listener to an event and element
and has no further tweaks. This is the common use case for event handling.
Arguments:
event
(string) - the event to listen onName callback
(function) - the event listener
Example:
DebounceEvent
The Debounce
is most suitable if an event is triggered quite often
but executing the event listener is called only after a certain wait time.
Arguments:
event
(string) - the event to listen onName callback
(function) - the event listenerwait
(number) - the amount of milliseconds to wait before the event listener is calledimmediate
(boolean) - if true, the event listener is called right when the event started
Example:
ThrottleEvent
Arguments:
event
(string) - the event to listen onName callback
(function) - the event listenerlimit
(number) - the amount of milliseconds to wait before the event listener is called
The Throttle
is similar to the Debounce
. The important
difference is that the event listener is called after the configured wait time
during the overall event time.
If an event time is about 2000ms and the wait time is configured to be 100ms, the event listener gets called up to 20 times in total (2000 / 100).
Example:
RequestAnimationFrameEvent
The Request
binds its execution to the browser's
Request
API. It is suitable for event listeners that
manipulate the DOM.
Arguments:
event
(string) - the event to listen onName callback
(function) - the event listener
Example: