Elevating Node.js Development: Extending EventEmitter

KolaKachi
This entry is part 20 of 35 in the series Node.js Unleashed: A Comprehensive Guide for Developers

Welcome back to our Node.js journey! In our previous adventure, we explored the Events Module and danced with the Event Emitter class. Today, we’re about to take our Node.js craftsmanship to new heights by crafting our own module, seamlessly extending the capabilities of the Event Emitter. However, this time, we’re entering the world of coffee as we unveil the magic of an event-driven coffee ordering system.

Crafting the CoffeeShop Module

Let’s start by creating a module that mirrors the operations of a coffee shop. In the script named coffeeshop.js, we define a CoffeeShop class with a constructor to initialize an order counter. Two methods, placeOrder and displayOrderNumber, orchestrate the placement and display of coffee orders.

// coffeeshop.js
class CoffeeShop {
    constructor() {
        this.orderNumber = 0;
    }

    placeOrder() {
        this.orderNumber++;
        this.emit('order', 'medium', 'latte'); // Emitting the 'order' event
    }

    displayOrderNumber() {
        console.log(`Current order number: ${this.orderNumber}`);
    }
}

module.exports = CoffeeShop; // Exporting the class for use in other modules

Harmonizing CoffeeShop with Events

Now, in our main script (index.js), we transition from the simple script we had before and introduce the CoffeeShop class. We instantiate it, place a coffee order, and display the order number.

// index.js
const EventEmitter = require('events');
const CoffeeShop = require('./coffeeshop');

const coffeeshop = new CoffeeShop(); // Instantiating the CoffeeShop class

coffeeshop.placeOrder();
coffeeshop.displayOrderNumber();

This sets the stage for our coffee shop, but there’s an exciting twist awaiting us. We want our coffee shop to embrace the elegance of event-driven architecture using the Events Module.

Embracing Inheritance: CoffeeShop Inherits EventEmitter

In JavaScript, the magic of extending one class to inherit the functionality of another opens doors to a world of modular possibilities. Our CoffeeShop class is about to inherit the prowess of the EventEmitter class, giving it the ability to emit and respond to events.

// coffeeshop.js - Extending the CoffeeShop class
const EventEmitter = require('events');

class CoffeeShop extends EventEmitter {
    constructor() {
        super(); // Invoking the parent class constructor
        this.orderNumber = 0;
    }

    // Existing methods remain unchanged

    placeOrder() {
        this.orderNumber++;
        this.emit('order', 'medium', 'latte'); // Emitting the 'order' event
    }
}

module.exports = CoffeeShop;

This elegant inheritance is achieved using the extends keyword and invoking super() within the constructor, establishing a seamless connection with the EventEmitter class.

Orchestrating Events: Listener Symphony

With our CoffeeShop class now an event-emitting maestro, let’s harmonize it with listeners. Back in index.js, we register a listener for the ‘order’ event, capturing the size and type of coffee details.

// index.js - Attaching an event listener
coffeeshop.on('order', (size, type) => {
    console.log(`Order received: Making a ${size} ${type}`);
});

Introducing Another Module: CoffeeMachine

But the symphony doesn’t end here. We’re adding another layer to our modular composition. A CoffeeMachine class is defined in a separate file (coffeemachine.js). This class, akin to an encore, prepares complimentary snacks based on the coffee order size.

// coffeemachine.js
class CoffeeMachine {
    prepareSnack(size) {
        if (size === 'large') {
            console.log('Preparing complimentary snack');
        }
    }
}

module.exports = CoffeeMachine;

Extending the Modular Symphony

Brace yourself for the grand finale! Back in index.js, we import and utilize the CoffeeMachine class, seamlessly integrating it into our event-driven orchestration.

// index.js - Integrating the CoffeeMachine module
const CoffeeMachine = require('./coffeemachine');
const coffeeMachine = new CoffeeMachine();

coffeeshop.on('order', (size) => {
    coffeeMachine.prepareSnack(size); // Invoking the prepareSnack method from the CoffeeMachine class
});

coffeeshop.placeOrder(); // Triggering the event and cascading the symphony
coffeeshop.displayOrderNumber(); // Displaying the current order number

Unleashing Modular Brilliance

Execute node index.js in your terminal, and behold the brilliance of modular design. Our coffee shop, seamlessly extending the EventEmitter class, orchestrates events and collaborates with the CoffeeMachine module, resulting in a flavorful and well-structured Node.js application.

What Lies Beyond

As we conclude this chapter, remember the power of inheritance and modular design. The forthcoming chapters of our Node.js saga will delve into the remaining built-in modules, unveiling their secrets and intricacies.

Thank you for embarking on this modular symphony with us. Don’t forget to subscribe for more Node.js revelations, and I’ll rendezvous with you in the next movement of our orchestration.

Series Navigation<< A Deep Dive into the Events ModuleDecoding the Digital Tapestry: Unraveling Character Sets and Encoding in Node.js >>

Leave a Reply

Your email address will not be published. Required fields are marked *