node.js - 如何替换 Node JS 事件接收器的 `this`?

标签 node.js eventemitter

是否可以替换this发送事件时的上下文?

var that = {}, obj = new myType();

// how to pass `that` as the calling context?
obj.emit('myEvent', data);

obj.on('myEvent', function () {
    // I need it to arrive with `this`=`that`
});

我正在使用标准EventEmitter继承方式:

在我的类型的开头:

events.EventEmitter.call(this);

遵循类型函数:

myType.prototype.__proto__ = events.EventEmitter.prototype;

但这似乎会覆盖任何 emit与我在 myType 中指定的任何上下文功能。当我需要不同的this时上下文,我不知道如何发送它。

最佳答案

如果您想在每次发送事件时更改上下文,您可以将另一个包含上下文的对象传递给发射函数。然后我们可以编写一个包装函数,自动将新上下文绑定(bind)到处理程序。

例如:

function withContext(fn) {
   return function(data, context) {
       return fn.call(that, data);
   }
}

// how to pass `that` as the calling context?
obj.emit('event_1', data, context_1);
obj.emit('event_2', data, context_2);


obj.on('event_1, withContext(handler_1));
obj.on('event_2', withContext(function(data) { 
  this === that // true;
});

关于node.js - 如何替换 Node JS 事件接收器的 `this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687571/

相关文章:

node.js - 未在 windows 中设置的环境变量

node.js - mocha/chai 和 ES6 Promise 的奇怪断言失败

node.js - firebase/messaging 不提供名为 getToken 的导出

angular - 如何知道组件当前是否是路由器导出中加载的组件

angular - 在 Angular 的整个应用程序中发出和广播事件

javascript - EventEmitter() 的 "Static methods"

node.js - ExpressJs : Differentiating between two similar routes

node.js - "composeEnhancers"不是 ReactJS 中的函数

javascript - Node.js EventEmitter `on` 事件不能 "see"类属性

带有回调的 Angular @Output