节点事件发射器 - 如何将类转换为类语法

时间:2017-10-17 14:16:03

标签: node.js class eventemitter

我找到了一个创建事件Emitter类的示例,它接受一个流(tcp net connection)并从它从该流中提取的数据事件中发出它自己的自定义事件。

无论我做什么,我都无法重制它将es6类​​语法。我在节点文档中看到这应该是可能的。但我有一个弱的OOP背景,我只是无法让事情发挥作用。

我确信有人可以轻易搞清楚。这是原始类(用于扩展的es5样式构造函数/ util模块...)

const MsgClient = function(stream) {
  events.EventEmitter.call(this);  

  let self = this, buffer = "";

  stream.on("data", (data) => {
    buffer += data;
    let boundary = buffer.indexOf("\n");
    while (boundary !== -1) {
      let input = buffer.substr(0, boundary);
      self.emit("message", JSON.parse(input));
      buffer = buffer.substr(boundary + 1);
      boundary = buffer.indexOf("\n");
    }
  })
}

util.inherits(MsgClient, EventEmitter); // from require("events").EventEmitter

在我的天真中,我尝试了以下内容,但是我没有背景,当它不起作用时不会迷路。如果你不习惯它,“这个”真的很复杂......

class MsgClient extends EventEmitter {
  constructor(stream) {
    super();
    this.stream = stream;
    this.buffer = "";
    self = this;
  }

  stream.on("data", (data) => {
    buffer += data;
    let boundary = buffer.indexOf("\n");

    while (boundary !== -1) {
      let input = buffer.substr(0, boundary);
      self.emit("message", JSON.parse(input));
      buffer = buffer.substr(boundary + 1);
      boundary = buffer.indexOf("\n");
    }
  }) 
};

如果有人可以帮助甚至指出我的写作方向,我将不胜感激。

3 个答案:

答案 0 :(得分:2)

试试这个:

class MsgClient extends EventEmitter {
  constructor(stream) {
    super();
    this.stream = stream;
    this.buffer = "";

    stream.on("data", (data) => {
      buffer += data;
      let boundary = buffer.indexOf("\n");

      while (boundary !== -1) {
        let input = buffer.substr(0, boundary);
        this.emit("message", JSON.parse(input));
        buffer = buffer.substr(boundary + 1);
        boundary = buffer.indexOf("\n");
      }
    })
  }
};

答案 1 :(得分:0)

或试试这个,以前的答案也应该有效,但可能你想这样做。

class MsgClient extends EventEmitter {
  constructor(stream) {
    super();
    this.stream = stream;
    this.buffer = "";
    this.onData = this.onData.bind(this);
    stream.on("data", this.onData);
  }

  onData(data){
    buffer += data;
    let boundary = buffer.indexOf("\n");

    while (boundary !== -1) {
      let input = buffer.substr(0, boundary);
      this.emit("message", JSON.parse(input));
      buffer = buffer.substr(boundary + 1);
      boundary = buffer.indexOf("\n");
    }
  }
}

编辑:现在应该编译和工作

答案 2 :(得分:0)

最终工作得很好:

class MsgClient extends EventEmitter {
  constructor(stream) {
    super();
    let buffer = "";

    stream.on("data", (data) => {
      buffer += data;
      let boundary = buffer.indexOf("\n");

      while (boundary !== -1) {
        let input = buffer.substr(0, boundary);
        this.emit("message", JSON.parse(input));
        buffer = buffer.substr(boundary + 1);
        boundary = buffer.indexOf("\n");
      }
    });
  }
};

我所缺少的是整个" stream.on"方法正在构造函数中声明,所以感谢指出这一点。此代码现在可以像原始es5类型一样工作。