Nodejs EventEmitter - 定义侦听器函数的范围 [英] Nodejs EventEmitter - Define scope for listener function
本文介绍了Nodejs EventEmitter - 定义侦听器函数的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要这样的工作:
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');
但是,不幸的是,听众甚至没有被调用。有没有办法做这个W / EventEmitter?我可以 Function.bind
给听众,但是,我真的希望 EventEmitter
有一些特别的(或明显的; )方法这样做...
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...
感谢您的帮助!
推荐答案
不,因为侦听器中的此
值是事件发射器对象。
No, because the this
value in the listener is the event emitter object.
但是你能做什么这是吗
var scope = {
...
};
scope._events = test._events;
test.emit.call(scope, ...);
您的事件处理程序未被调用的原因是因为所有处理程序都存储在<$ c $中c> ._ events 所以如果你复制 ._ events
就可以了。
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.
这篇关于Nodejs EventEmitter - 定义侦听器函数的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文