我有一個類,它在NodeJS中管理我與我的套接字的連接。每當無法建立連接或丟失連接時,我想設置一個間隔以保持重試連接。但是,如果我調用setInterval
函數,則作爲參考傳遞的方法現在處於setInterval
的範圍內。我的套接字類中的方法現在不再可用,除非我有一些巨大的嵌套語句,否則我無法重新連接套接字。主要的問題是我在connect()
方法中創建的事件偵聽器現在不再在setInterval()
的範圍內可用。在javascript中使用setInterval時保持在類的範圍內
關於如何使這項工作的任何想法?
class SocketClass {
constructor() {
this.socket = {}
this.port = 0
this.host = ''
this.intervalID = null
}
connect(port, host) {
this.port = port;
this.host = host;
this.connectImpl()
this.socket.on('error',() => this.errorEventHandler())
this.socket.on('close',() => this.closeEventHandler())
}
connectEventHandler() {
console.log('Connected!')
if (this.intervalID !== null) {
clearInterval(this.intervalID);
}
}
errorEventHandler() {
console.log('Error!')
}
connectImpl() {
console.log('Trying to connect...')
this.socket = require('net').Socket().connect(this.port, this.host)
}
closeEventHandler() {
console.log('Connection lost')
this.intervalID = setInterval(() => this.connectImpl(), 1000)
// this.connectImpl() is called correctly but the event
// handlers defined in the constructor are now no longer bound
}
}
export default new SocketClass
我發現downvotes令人難以置信的難以捉摸。我的問題很簡單,包括代碼。有人真的喜歡粉碎那個downvote按鈕.. – Ortix92
擊敗我 - 有人downvoted我的完美的答案太... – Alnitak
至於明確:_「我通過作爲參考的方法現在在setInterval的範圍內」_ - 沒有,那是不正確的。 _「我的套接字類中的方法現在不再可用」_ - 不正確。 _「我在connect()方法中創建的事件偵聽器現在不再在setInterval()的範圍內可用(_」 - 也是不正確的。 – Alnitak