Refactoring using an event-driven approach: part 2
In the previous article we learnt what event-driven programming is and how you can leverage it to refactor your code. We also learnt circumstances under which you may use an event-driven approach instead of other conventional approaches. I highly recommend that you read that first.
In this article, we shall learn how event-driven systems are built from the ground up. We shall use
In any Event System there must be a defined set of functions:
1. Registration function
This function is usually defined by an
on() method. It registers an event listener which is an anonymous function or callback function.
An event listener is a function that defines the actions to be taken once the event is dispatched at any given point in your program.
on() method may also take on an optional
target context parameter that defines the context that the listener is called from.
The usual form of an event registration function is as follows:
EventEmitter.on(event, listener, target|context?)
on() method is very straightforward. We just need to push the event and it’s listener to an array or object which we’ll use throughout the Event Emitter object.
EventEmitter.js file and add the following code:
2. De-registration function
This method is usually defined as an off() method. It basically removes the event listeners for a given event from the list of registered event listeners.
I’ve added a helper method to reduce duplication as we add more methods to the Event Emitter.
3. Dispatching function
In order to fire/dispatch events, we have to call the listeners attached to the given event and also keep track of them.
First, add a
fireEvents array to the EventEmitter class. This array keeps track of all dispatched events.
The following snippet shows the implementation of a dispatch function:
4. Clearing function
A clearing function just deletes both the registered and fired listeners. It effectively resets everything back to default.
Usually denoted as
An Event Emitter is like a real-life event manager who ensures that the various events scheduled for the calendar are well organized with the right people (listeners/handlers) and occur at the right place (target/context).
In the next tutorial, we’ll refactor the game and show how we can use this class to refactor some of the code in the little game we built.