2014-11-21 140 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! 
    } 
}