将事件发射器连接到节点中每个ES6类的实例

时间:2017-08-10 03:11:32

标签: node.js ecmascript-6 eventemitter es6-class

我正在尝试将类的每个实例与事件发射器相关联。我正在尝试以下方法:

const events = require("events");
const eventEmitter = new events.EventEmitter();

class Camera {
    constructor(ip) {
        this.ip = ip;

        eventEmitter.on("recordVideo", function() {
            this.recordClip();
        });
    }

    recordClip() {
        console.log("record " + this.ip);
    }
}

var cam = new Camera("0.0.0.0");
eventEmitter.emit("recordVideo");

但我回来了:

TypeError: this.recordClip is not a function

我怎样才能让我班级的每个实例都听取这个事件?

2 个答案:

答案 0 :(得分:1)

这是因为回调函数中的上下文没有引用您期望的内容。添加箭头功能。

const events = require("events");
const eventEmitter = new events.EventEmitter();

class Camera {
   constructor(ip) {
     this.ip = ip;

      eventEmitter.on("recordVideo", () => {
        this.recordClip();
      });
   }

   recordClip() {
      console.log("record " + this.ip);
   }
}

   var cam = new Camera("0.0.0.0");
   eventEmitter.emit("recordVideo");

以下是一些文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

答案 1 :(得分:1)

您的问题是eventEmitter位于事件发射器的上下文中,而不是类。因此,recordClip没有eventEmitter.on("recordVideo", () => { this.recordClip(); }); 作为方法。您需要使用箭头函数在词法上绑定回调:

(就我个人而言,我认为这是最好的,也是最现代/可读的方式)

eventEmitter.on("recordVideo", function() {
    this.recordClip();
}).bind(this);

或者,您需要绑定适当的范围:

this

或者您可以通过self方法提及class Camera { constructor(ip) { this.ip = ip; const self = this; //assign this to self eventEmitter.on("recordVideo", function() { self.recordClip(); //use self, not this here }); } recordClip() { console.log("record " + this.ip); } }

Overlapped Recycle