Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs EventEmitter - Define scope for listener function

I'd like to have something like this work:

var Events=require('events'),
    test=new Events.EventEmitter,
    scope={
        prop:true
    };

test.on('event',function() {
   console.log(this.prop===true);//would log true
});
test.emit.call(scope,'event');

But, unfortunately, the listener doesn't even get called. Is there any way to do this w/ EventEmitter? I could Function.bind to the listener, but, I'm really hoping EventEmitter has some special (or obvious ;) way to do this...

Thanks for the help!

like image 285
Lite Byte Avatar asked Nov 04 '11 06:11

Lite Byte


1 Answers

No, because the this value in the listener is the event emitter object.

However what you can do is this

var scope = {
  ...
};
scope._events = test._events;
test.emit.call(scope, ...);

The reason your event handler did not get called is because all the handlers are stored in ._events so if you copy ._events over it should work.

like image 95
Raynos Avatar answered Oct 06 '22 13:10

Raynos