2014-11-21 1 views
0

크롬 앱에서 시리얼 장치와 통신하려고합니다. 문제는 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

+0

코드 – PizzaMartijn

+0

을 추가했습니다. console.log ("Connected", service)로 로그를 변경하고 결과를 게시하십시오. – sowbug

답변

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

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! 
    } 
}