What are Event Systems?
Event systems enables us to create dynamic code while minimizing decoupling between entities. When I use the word event systems I am referring to any network of publishers and subscribers. The most ubiquitous example of this would be a simple onclick listener as seen in jQuery:
$('#el').on('click', callback);
How would you implement the above functionality? How can we 'listen' to an
object? How can we activate callback
only once that object is clicked? The
naive approach would be to simply create a
setInterval
to continuously check the state of the object and compare it
to it's previous state. The most obvious problem with this way of implementing
an event listener
is that this process would be very expensive computationally. Modern event
systems provide us with a much more effecient way.
Modern Event Systems Overview
Instead of having another object continuously check for a state change on a target object and then executing some behavior when a state change has occured, we can maintain a datastore of behaviors on the target object itself and have those behaviors execute when specific events are triggered on it. In other words, We can associate a datastore of functions on a target object to a specific event. When the event is triggered on that target object, then the target object itself invokes all the functions in its datastore. In this way, putting a click listener on a target object, really just adds a new behavior to the objects datastore.
Registering an interesting
The process of sending a callback to a target object to be executed when a certain state changes are triggered on that target object is called registering an interest. In our previous example:
$('#el').on('click', callback);
It could be said that jQuery is registering an interest on the #el
element. On the surface it appears the on
listener is
actively listening to the #el
element. However, the on
listener is not really
listening to the #el
element per se. In reality jQuery
is really just sending the provided callback to #el
when the
on
method is
executed during runtime. When the click state is finally triggered on
#el
, it fires all the functions in its datastore. This gives the
illusion that the on
method is actively 'listening' to
#el
but in reality allon
does is register an
interest with #el
and as a result #el
is decorated
with new behavior which will be executed only when certain conditions are met in
terms of its state.
3 Key Attributes of Event Systems
- Event listeners
- Data stores
- Triggers
Additional Resources
If you want to go deeper on concepts relating to design patterns then I highly recommend the JavaScript Design Patterns book.