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');
但不幸的是,听众甚至没有被叫到。 有没有办法做到这一点与EventEmitter? 我可以Function.bind
给侦听器,但是,我真的希望EventEmitter
有一些特殊的(或明显的)方法来做到这一点…
谢谢您的帮助!
不,因为监听器中的this
值是事件发射器对象。
但是你可以做的是这个
var scope = { ... }; scope._events = test._events; test.emit.call(scope, ...);
你的事件处理程序没有被调用的原因是因为所有的处理程序都存储在._events
所以如果你复制._events
它应该工作。
这将无法正常工作,并只发射有一个方便的方式来传递参数,但没有设置this
。 看起来你必须自己做一些有约束力的东西。 但是,您可以将其作为parameter passing给它:
test.on('event',function(self) { console.log(self.prop===true);//would log true }); test.emit('event', scope);
当Google在NPM中search一个包时,我遇到了这个post:
var ScopedEventEmitter = require("scoped-event-emitter"), myScope = {}, emitter = new ScopedEventEmitter(myScope); emitter.on("foo", function() { assert(this === myScope); }); emitter.emit("foo");
充分披露,这是我写的一个包。 我需要它,所以我可以有一个EventEmitter属性发出的包含对象的对象。 NPM包页面: https : //www.npmjs.org/package/scoped-event-emitter