将回调函数传递给module.exports吗?

时间:2019-07-09 14:18:30

标签: javascript node.js dom-events serverside-javascript

我写了带有模块导出功能的USB检测代码,我想发送 还会触发该事件的回调函数。

这里:

module.exports = class USBDetection {
  constructor() {
    this.usb = require('usb');
    this.usbDetect = require('usb-detection');
  }

  startMonitoringDevices() {
    this.usbDetect.startMonitoring();
    // Detect add/insert
    this.usbDetect.on('add', function(device) {
      callback('add', device);
    });
    this.usbDetect.on('add:vid', function(device) {
      callback('add', device);
    });
    this.usbDetect.on('add:vid:pid', function(device) {
      callback('add', device);
    });

  }
};

如何将callback传递给模块?

2 个答案:

答案 0 :(得分:1)

因此在您的模块中:

  startMonitoringDevices(options = {}) {
    this.usbDetect.startMonitoring();
    // Detect add/insert
    this.usbDetect.on('add', function(device) {
      if (options.add !== undefined) {
          options.add('add', device);
      }
    });
    this.usbDetect.on('add:vid', function(device) {
      if (options.add !== undefined) {
          options.add('add', device);
      }
    });
    this.usbDetect.on('add:vid:pid', function(device) {
      if (options.add !== undefined) {
          options.add('add', device);
      }
    });
  }

在您的呼叫者中

const usbDetect = new USBDetection();

usbDetect.startMonitoringDevices({
     add: function(eventType, device){
          console.log('it does its job');
     }
});

答案 1 :(得分:1)

module.exports = callback => {
    const usb       = require('usb');
    const usbDetect = require('usb-detection');

    return {
        usb,
        usbDetect,
        startMonitoringDevices: () => {
            // Detect add/insert
            usbDetect.on('add', function(device) {
                callback('add', device);
            });
            ...
            usbDetect.startMonitoring();
        },
    };
};