Events are the backbone of Node.js. Node.js is an event-based API that uses events to manage complex operations. So, what are events?
The EventEmitter class can be used as is or can be extended with your own code. The class has three important methods for controlling events; the methods are: on, once, and emit. Methods on and once register functions to that event name; emit triggers the functions related to that event name in the order they were added. Furthermore, you can pass any parameter type to the emit method for your register functions to use. If you’re working with games or even used to regular programming, events may not seem useful. But, effective use of events can make your code cleaner. So, when would you use events?
Practical Example Of Event Use
Events are a clean way to handle states within a class or for creating links between different classes in your code. For example, you may have a class called car and tracker. When the car starts, you want to track the car. You could have all the cars call a function on the tracker to pass an instance of themselves to the tracker. Or, you could emit and event from the car that passes that information to the tracker. Using events can improve the code base and makes it easier to understand with a small event-based solution to getting information between classes that shouldn’t directly reference each other. Now, here’s an example of creating a state machine using events:
Here’s the ES5 Version:
Here’s the console output:
As you can see we define a couple events with on and once methods. We use our codeColor method to emit the initialize and changeState events. Because initialize is registered to a once method, it will only appear once as “Initial State: Blue Ocean”. The changeState event emits the changedState event, logging the state of our stateMachine when called. Using the emit method, we can have this executed anywhere in our code base without calling the registered function directly. If we wanted, we could have made StateMachine inherit from EventEmitter, and as events are emitted, it changes its internal state. One example of this is the Stream class in Node.js. A stream has different events emitted based on changes within its internal state such as receiving data or when receiving data has ended and more. Anyway, let’s look at the output of the code above.