Nodejs EventEmitter - Define scope for listener function

不羁岁月 提交于 2019-11-29 13:58:07

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.

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

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

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