我正在尝试使用 NodeJS 模块“pcsc-lite”与读卡器进行通信。如果您想查看该模块:https://github.com/santigimeno/node-pcsclite .
我正在寻找一种使用我自己的方法向我的阅读器发送数据序列的方法。因为,该模块是基于事件的。因此,我必须声明两个监听器(一个在另一个中)才能调用 send 方法。
例如:
module.on("reader", function(reader){
//...
reader.on("status", function(status){
//...
reader.connect({ share_mode : this.SCARD_SHARE_SHARED },function(err, protocol) {
//This is the method I want to be able to call "when I need it"
reader.transmit(...);
});
});
});
我想像这样调用传输方法:
function send(...){
reader.transmit(...);
}
我认为有一种方法可以做到这一点,但我似乎有点沉迷于我的 C/Java 编程习惯。
提前致谢。
最佳答案
如果您的阅读器是单例,您可以在回调之外声明它,然后在准备好时分配该变量。在不了解更多信息的情况下,这是一个简单的示例:
let reader; // we prepare a variable that's outside of scope of it all.
// your `send` function
function send(params) {
let stuff = doStuffWithParams(params);
reader.transmit(stuff, callback);
}
// we take out init stuff too
function initialize() {
// we know reader variable is already initialized.
reader.on('status', function() {
reader.connect({
share_mode : this.SCARD_SHARE_SHARED
},function(err, protocol) {
// send.
send();
// or even better, emit some event or call some callback from here, to let somebody outside this module know you're ready, then they can call your `send` method.
});
});
}
// now your module init section
let pcsc = require('pcsclite')();
pcsc.on('reader', function(r) {
// assign it to our global reader
reader = r;
initialize();
});
注意:不要调用你的变量模块
,它指的是当前正在执行的文件,你可能会得到意想不到的行为。
关于javascript - 如何在闭包之外调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34026491/