2014-11-21 48 views
0

我正試圖與Chrome應用程序中的串行設備進行通信。我遇到的問題是來自chrome.serial函數的回調在錯誤的範圍內。如果我把所有東西都放在全局範圍內,但是如果我嘗試在「類」中調用任何東西,那麼一切都在工作,那麼什麼都不會發生chrome.serial.connect回調範圍問題

service = {}; 
service.state = "disconnected"; 
service.connect = function(){ 
    chrome.serial.connect(service.config.port, options, function (connectionInfo) { 
     console.log("Connected"); // This works 
     service.state = 'connected'; // This doesn't change the variable 
     this.state = 'connected'; // This also doesn't change it 
    } 
} 
+0

你可以顯示'state'變量聲明的代碼嗎? – lostsource 2014-11-21 23:15:46

+0

我已添加代碼 – PizzaMartijn 2014-11-21 23:36:33

+0

將日誌更改爲console.log(「已連接」,服務)併發布結果。 – sowbug 2014-11-22 16:13:43

回答

2

之前,您也可以只是你的回調函數的範圍綁定到你的服務對象圍繞這個工作。

service = {}; 
service.state = "disconnected"; 
service.connect = function() { 
    chrome.serial.connect(this.config.port, options, function (connectionInfo) { 
     console.log("Connected"); // This works 
     this.state = 'connected'; 
    }.bind(this)); 
} 
+0

這是比我的解決方法更好的解決方案 – PizzaMartijn 2014-12-10 15:00:35

0

我已經保存在一個局部變量的範圍調用這個函數

service = {}; 
service.state = "disconnected"; 
service.connect = function(){ 
    var scope = this; 
    chrome.serial.connect(service.config.port, options, function (connectionInfo) { 
     console.log("Connected"); // This works 
     service.state = 'connected'; // This doesn't change the variable 
     this.state = 'connected'; // This also doesn't change it 
     scope.state = 'connected'; // This works! 
    } 
}