暂时禁用事件侦听器并稍后重新绑定

Temporarily disable event listeners and rebind later

我有一个基本的 websocket 程序。我有一个数据回调,它分析消息并发出一个事件。这是一个最小的示例,显示了需要显示的所有内容。

Cylon = new EventEmitter();

Cylon._createConnection = function(name) {
  let self = this;
  let socket = net.connect(this.config.port, this.config.host);

  socket.on('data', Meteor.bindEnvironment(function (data) {
    let args = _.compact(data.toString('ascii').split(':'));
    args.push(name);
    self.emit.apply(self, args);
  }));

  return socket;
}

Cylon._commands = Cylon._createConnection('commands');

Cylon.on('TriggerActivated', (trigger) => {
  console.log(`Trigger warning! ${trigger}`);
});

问题出在这里:存在一个 echo 命令,它将简单地将信息作为字符串传递到套接字上。意思是 Cylon.on('TriggerActivated') 可以通过 MG "TriggerActivated:test"

来欺骗

所以我的问题是:有没有办法暂时解绑所有的事件监听器?

Cylon._sendCommand = function (command) {
  check(command, String);
  if (command.splice(0,2) === 'MG') {
   // Unbind event listeners
   Cylon._commands.on('data', console.log);
   Cylon._commands.write(command);
   // Rebind all previous event listeners here
  }
}

JavaScript/node可以吗?

你可以这样做(未测试):

// get current listeners
var listeners = Cylon.listeners(command)

// Unbind event listeners
Cylon.removeAllListeners(command);

// do your special processing
Cylon._commands.on('data', console.log);
Cylon._commands.write(command);

// Rebind all previous event listeners here
listeners.forEach(function(listener) {
    Cylon.on(command, listener);
};

但最好不要发出事件:

  socket.on('data', Meteor.bindEnvironment(function (data) {
    if (data.splice(0,2) !== 'MG') {
        let args = _.compact(data.toString('ascii').split(':'));
        args.push(name);
        self.emit.apply(self, args);
    } else {
        console.log(data);
    }
  }));

或者类似这样的东西(发出一个你只订阅它的特殊事件)。