Events in NodeJS
Introduction
- Node.js is an asynchronous event-driven architecture
- All objects that emit events are instances of the EventEmitter class
- Event names are camel-cased strings
- When the EventEmitter object emits an event, functions attached to that specific event are called synchronously
Implement event
- eventEmitter.on() method is used to register listeners
- eventEmitter.emit() method is used to trigger the event
const EventEmitter = require('events'); class ShopEmitter extends EventEmitter { } const cartEmitter = new ShopEmitter(); cartEmitter.on('addItem', function (params) { console.log('Item added to cart'); }); let params = { id: 1 }; cartEmitter.emit('addItem', params); // output // Item added to cart