Nodejs EventEmitter - Define scope for listener function

て烟熏妆下的殇ゞ 提交于 2019-11-28 07:27:48

问题


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!


回答1:


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.




回答2:


That won't work, and emit only has a convenient way to pass parameters, but none for setting this. It seems like you'll have to do the binding stuff yourself. However, you could just pass it as a parameter:

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



回答3:


I came across this post when Google searching for a package in NPM which handles this:

var ScopedEventEmitter = require("scoped-event-emitter"),
    myScope = {},
    emitter = new ScopedEventEmitter(myScope);

emitter.on("foo", function() {
    assert(this === myScope);
});

emitter.emit("foo");

Full disclosure, this is a package I wrote. I needed it so I could could have an object with an EventEmitter property which emits for the containing object. NPM package page: https://www.npmjs.org/package/scoped-event-emitter



来源:https://stackoverflow.com/questions/8005563/nodejs-eventemitter-define-scope-for-listener-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!