Event
Twilight JavaScript SDK uses Event-Driven Architecture, which is a modern design approach centred around data that represents "events" (i.e., a product has been added to the cart). In event-driven programming, an event is the result of a single or multiple actions. Subscribers can listen to that event and take action after it is released by the emitter. In other words, emitters can send events containing data that subscribers can use, and subscribers can use the data to do actions.Twilight uses EventEmitter2, which is an implementation of the EventEmitter module found in Node.js. It not only outperforms EventEmitter in benchmarks and is browser-compatible, but it also adds a slew of new non-breaking functionality to the EventEmitter interface. In this article, we will learn how to use the Twilight events and actions with easy steps and examples.📙 What you'll learn#
Trigger an event#
Twilight includes a long list of events, such as codeNotSent
, verificationFailed
, failedLogout
, and many more. These events that can be triggered by the emitter's 'emit()' method. This method causes the event to be pushed using the data that the developer has provided.For example, the developer may create an event based on verified login by the user. Simply, the emit()
method can be called with a list of parameters. These parameters state the event's action and the passed data along with it as below:Twilight provides an additional way to create these events in a more readable and clearer method. With this alias, the developer can create the following chine of methods around salla.trigger_name.event.action_name()
:Listening to the event#
After creating the event along with its list of data, the next step is to implement an appropriate listener for that event. In Twilight, this can be achived using several methods:Using the alias method salla.event.{modul name}.{action name}()
, where the trigger, action, can be auth
during the login, and the result of that action is verified
.
Modul name can be any of the main module within the API, such as auth
, cart
, etc.
Action name can be any action included within the module, such as onVerified
in the auth
module.
Using the event name and result directly along with an anonymized function to perform the needed action based on the event result.
Adding a one
time listener for the event along with an anonymized function to perform the needed action based on the event result.
The onlyWhen
event triggers a callback only once when the event occurs. If the event has already been emitted, it runs immediately; otherwise, it waits for the event. This ensures responsive handling of past and future events.
Modified at 2025-02-06 07:37:41