2015-12-01 27 views
1

我正在嘗試使用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編程習慣。

在此先感謝。

+0

這不是閉包而是回調函數。只有在回調函數中才能得到reader對象。你可以告訴你的用例,當你想調用'reader.transmit()' – Chandan

+0

我想創建一個小的API。事實上,目標是實例化一個新的對象,例如'myObj',並且能夠在循環中調用'myObj.send(params)',例如 –

+2

但是您不確定什麼時候您的'reader'準備好所謂的「傳輸」方法也是如此。我會建議利用相同的承諾。 – Chandan

回答

0

如果您的讀者將是一個單身人士,您可以在回調之外聲明它,然後在準備就緒時分配變量。不知道更多,這裏有一個簡單的例子:

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(); 
}); 

注意:不要叫你的變量module,它指的當前正在執行的文件,你可以得到意外的行爲。