State Events
Advanced State Operations - Events
Introduction
In the last chapter, we learned how we can use the state subscription methods to react to different actions taken on the state. Now we will learn to create custom events for our own purposes, that might be retrieving localStorage data when the component loads, or such things.
There are two methods of the State
that does this,
registerEvent(...)
registers the custom event with a callback, that is expected to be called when the following custom event is emited, usingemitEvent(...)
which takes the name of the event as well as any data that might be related to it. The data is then passed to the callback function and the event is completed.
You cannot register multiple functions under a single event name, which is simillar to the document.addEventListener() method.
Here is an example that retrieves the value from the localStorage:
In the above code, we declared the event which will take string
data, the name of the item to retrieve from the localStorage. If it does not exists, it will simply set the text to No data, which means we can do state operations directly from event callbacks.
Purpose
The purpose is again to create fine grained reactivity that does not breaks, since it is easier to track errors in callback. Also, many of our upcoming libraries will use custom events to deliver super experience.
Last updated
Was this helpful?