将回调函数传递给 module.exports?
Pass Callback function to module.exports?
我写了一个带有模块导出的 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
传递给模块?
因此在您的模块中:
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');
}
});
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();
},
};
};
我写了一个带有模块导出的 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
传递给模块?
因此在您的模块中:
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');
}
});
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();
},
};
};