2013-02-27 3 views
0

나는 내가 호출 할 때 다음 코드를 사용하여 속성을 업데이트하기 위해 노력하고있어 "scanner.connect을()"메소드 속성을 업데이트하는 방법 : 나는 스캐너를 액세스 할 때 다음커피 스크립트 클래스에

class Scanner 
    ready: false 

    connect:() => 
     cordova.exec (status) => 
      console.log status 
      if status is 'connected' 
       @ready = true 
       console.log @ready 
     , 
     (error) -> 
      console.log error 
     , 
     "LineaProScanner", "ready", [] 

    scan:() -> 
     console.log 'start scan...' 
    stop:() -> 
     console.log 'stopping scan...' 

을 .ready 속성은 항상 false를 표시합니다.

scanner = new Scanner() 
scanner.connect() 
console.log scanner.ready // always shows false 

저는 CoffeeScript로 시작한 것입니다. 그래서 저는 잘못된 것을하고 있다는 것을 압니다. 그러나 저는 잘 모릅니다.

감사합니다.

+0

오, 예 상태가 "연결됨"을 반환했습니다. heh를 확인했습니다. – janex

+1

뚱뚱한 화살을 사용하여'연결 '하는 이유는 무엇입니까? – pdoherty926

답변

1

귀하의 coffeescript는 훌륭하게 보입니다. 실행 순서는 여기에 책임이 있으며, JS 프로그래머도 많이 걸리는 문제입니다.

저는 cordova.exec()이 비동기이기 때문에 전화를 걸기 전에 준비가되었는지 물어볼 것입니다.

것은 내가 옳다 있는지 확인하기 위해이 시도 :

scanner = new Scanner() 
scanner.connect() 
setTimeout (-> console.log scanner.ready), 1000 

너무 오래 스캐너가 1 초 이내에 자신을 준비시킨다으로 true를 기록해야한다고. 하지만이 코드를 어떻게 구성해야하는지는 아닙니다.


올바른 방법은 대신 자신의 콜백을 원하는 대신 setTimeout의입니다.

class Scanner 
    ready: false 

    # Accept a callback argument on the connect method. 
    connect: (onReady) => 
     cordova.exec (status) => 
      console.log status 
      if status is 'connected' 
       @ready = true 
       console.log @ready 

       # call the onReady callback if it was passed in 
       onReady?() 
     , 
     (error) -> 
      console.log error 
     , 
     "LineaProScanner", "ready", [] 

그리고 지금 당신은 간단하게 수행 할 수 있습니다

scanner = new Scanner() 
scanner.connect -> 
    console.log scanner.ready # should log `true` 
+0

감사합니다! 그게 날 많이 도와 줬어. – janex

0

이 줄에 =>을 단순화 할 수 있습니다 :

connect: (onReady) ->

클래스 메소드는 클래스 변수에 직접 액세스 할 수 있습니다. 그러나 메소드 내부의 함수는 그렇지 않습니다.