Nodejs EventEmitter - Define scope for listener function

前端 未结 3 835
野趣味
野趣味 2020-12-20 16:27

I\'d like to have something like this work:

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

test.on(\         


        
3条回答
  •  醉酒成梦
    2020-12-20 17:21

    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.

提交回复
热议问题