Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.

For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

You can fire one event that can cause 3 different actions to go off or have 1 event be used multiple different times.

Below is an example:

Our Events List

  • sendEmailNotification

  • sendSmsNotification

  • sendSlackNotification

Our Listeners List

  • event.listen('userHasCreatedANewListing'', sendEmailNotification)

  • event.listen('userHasRegistered', sendEmailNotification)

  • event.listen('userHasRegistered', sendSmsNotification)

  • event.listen('userHasRegistered', sendSlackNotification)

Notice how userHasRegistered triggers 3 different events and how sendEmailNotification can be used in more than 1 event listeners.

The Node.js Gift: EventEmitter

As JavaScript Developers, we are lucky enough to have the EventEmiter utility which is a built-in module that functions much like the traditional observer pattern. We'll see how to use this later on in the next chapter.

Examples of Events

Here are some examples of when to use events in your application

  1. Send an email after a user has registered.

  2. Logging user activity data.

  3. Sending an email and SMS to the user after he has deleted his account.

It can be hard at times to know what is considered an event. The difficulty comes when deciding whether to put something in the event layer or to just put it directly in the service layer.

The two heuristics that I follow when deciding whether something should be put in the service layer or the event layer are:

  1. Do I see a certain function that gets called come up over and over again at the end of each service layer, if I do, then maybe it's time to move it to the event layer for more re-usability.

  2. Do I see myself constantly adding new events inside the same service layer? If I do, then I would move those events to the event layer and try to chain the events through a single listener that can fire multiple events for that service.

Last updated