简体   繁体   中英

Node.js listen and emmit events

I have two classes and i want one class to be subscribed to the other. So something like this.

Class one:

while(1){ if(true){ //emmit some event }

Class two:

//wait for class one to emmit some data ,and then start working with the data

My question is, is there any method, module.. that can help me to implemented this behavior?

Use Node's built-in EventEmitter to implement emitting and listening events in both clients.

Example:

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
   console.log('an event occurred!');
});
myEmitter.emit('event');

The default class EventEmitter will do what you are asking for.

const myEmitter = new MyEmitter();

// Listen to event
myEmitter.on('event', (data) => {
  console.log(data);
});

// Emit event
myEmitter.emit('event', data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM