top of page
Logo der Online Agentur mdwp

EventEmitter

EventEmitter in React JS is an approach that allows communication between components indirectly, meaning a component can emit an event that is picked up by another component. This is most commonly used when you want to communicate between a parent and a descendant component, or between two components that are unrelated but share a common parent. EventEmitter is not a feature built into React JS itself but often utilized in combination with additional libraries that extend React's functionality, such as Node.js.

This process can be summarized in three steps:

1. Importing the 'events' module and creating an instance of EventEmitter.

2. Emitting an event: We use the 'emit' method from the EventEmitter instance to trigger an event in one component.

3. Listening to an event: We use the 'on' method from the EventEmitter instance in another component to listen for the emitted event.

Here's a basic example of how an EventEmitter can be used:

```javascript
// Importing Events module
var events = require('events');

// Creating an EventEmitter object
var eventEmitter = new events.EventEmitter();

// A function to be executed when the event is triggered
var showData = function somethingHappened() {
console.log('Something just happened!');
}

// Assign the event handler (showData) to an event named 'happening'
eventEmitter.on('happening', showData);

// Fire the 'happening' event
eventEmitter.emit('happening');
```

In this example, when the 'happening' event is emitted (triggered), the 'showData' function is called, which logs 'Something just happened!' to the console.

bottom of page