简体   繁体   中英

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. =(

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();

The event handler function is always called in the context of the object that emits the event, in this case b . In your example you could simply do

function a() {
  var self = this;

  ...
}

to remember a 's context, but I assume your real code is different and you may not have your event handler specified as a closure, so you can instead bind your handler to the desired object before setting it:

function a (){
    //this is my first function
    var b_obj = new b();
    b_obj.on('event', handlerFunction.bind(this));
}

In this case, your handlerFunction will always be called in the context of a . The bind method returns a new function that is bound to the object you provided, see Mozilla's documentation .

PS. You may want to phrase your questions clearer and provide better examples before you post in the future.

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