0

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?

DavidS
  • 13
  • 6
  • What's the question? – tbking Aug 18 '17 at 10:22
  • I think what you are actually referring to are threads not classes, a class is an object template, node.js is single threaded, it is asynchronous so you could create the functionality you want but not in a while loop like that, you must release execution back to node or the asynchronous part of node cannot work. – SPlatten Aug 18 '17 at 10:22
  • @tbking edited my post, sorry – DavidS Aug 18 '17 at 10:24
  • @SPlatten i can remove the while loop, it was just for an example. I just need someone to refer me to some module that can implement what i am asking. – DavidS Aug 18 '17 at 10:27
  • Inherit from [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter). – robertklep Aug 18 '17 at 10:28
  • @DavidS, it all depends on what you mean by subscribe? I'll post an answer with more detail. – SPlatten Aug 18 '17 at 10:29
  • @SPlatten Well i need the second class to wait until the first class returns true ( i have function in that class, that checks rows in some database and returns true/false ). And when the first class returns true ( the function in the class returns true ), then i need to call the second class that has other methods/functions. – DavidS Aug 18 '17 at 10:36
  • @DavidS, you don't need a class, you just need two method / functions, these can both be in the same class. – SPlatten Aug 18 '17 at 10:38
  • @SPlatten i need them to be in separate class for other reasons – DavidS Aug 18 '17 at 10:40

2 Answers2

0

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');
tbking
  • 8,796
  • 2
  • 20
  • 33
  • I have 1 function that checks the sql base and returns true, false. Where i need to call that function here ? – DavidS Aug 18 '17 at 10:32
  • In that function's callback, call `myEmitter.emit('SQL_RESULT');`. Define myEmitter in a file and import it. – tbking Aug 18 '17 at 10:34
0

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);
Sam
  • 3,070
  • 3
  • 20
  • 26