Search code examples
javascriptnode.jseventemitteremit

Node.js - Emit an event from another function/object


I'm struggling with this for almost 2hours and still not getting it.=( For explanation I got the following code.

var util = require('util');
var events = require('events').EventEmitter;

function a (){
    //this is my first function
    var b_obj = new b();
    b_obj.on('event',function(){
        console.log('Something happened!');
    });
};

function b (){
    //this is my second function
    events.call(this);
    this.emit('event');
};

util.inherits(b, events);
a();

So what I try to do is: I got a function called "a". This function calls a second function called "b". This function validates some data and emits events depending on the result of the validation.

What I found out is, that the listener works fine and the event is correct emitted. But, as it looks like the event is emitted in the context of function b and the listener works in the context of function a. For further investigations I added the following line to function b:

this.on('event', function(){
        console.log('event emitted!');
    });

And this works. Can anybody help me? I'm sure the solution is pretty simple. =(


Solution

  • If what you mean is inform the function a() when the validation process in function b() is complete, then just emit the event from b after doing the validation.
    I use setTimeout() for asyncronous example.

    var EventEmitter = require("events").EventEmitter;
    var theEvent = new EventEmitter();
    
    function a(){
      console.log('preparing validation..');
      theEvent.on('validationDone', function(validationResult){
        console.log('validation result is ' + validationResult);  // prints 'validation result is true' in the next 2 sec
      });
      b();
    }
    
    function b(){
      setTimeout(function(){
        var result = true;
        theEvent.emit('validationDone', result);
      }, 2000);
    }
    
    a();