2015-01-31 4 views
0

저는 며칠 동안이 문제로 어려움을 겪었습니다 ... 콜백 함수를 호출 할 수없는 것처럼 보입니다. 코드가 작동하기 때문에 코드가 작동하기 때문에 범위 문제가 있다고 생각합니다. 은 "클래스"분리 수동 등 모든 기능콜백 함수가 호출되지 않습니다.

테스트 I은 기본 타이머와 시각적 컨트롤을 분리, 타이머 오브젝트의 확장과 같은 작용하는 VisualTimer 객체

function VisualTimer(customConfig) { 
    // Create a new Timer object 
    var object = this; 
    this.timer = new Timer(object, function(data) { this.timerUpdated(data); }, function (data) { this.timerFinished(data); }); 

    // Set default configuration 
    this.config = { 
     // The ID's of the timer's control elements 
     pauseButtonId : "pause-timer", 
     startButtonId : "start-timer", 
     stopButtonId : "stop-timer", 
     // The ID's of the timer's display elements 
     hoursDisplayId : "hours-left", 
     minutesDisplayId : "minutes-left", 
     secondsDisplayId : "seconds-left", 
     // The ID's of the timer's input elements 
     hoursInputId : "hours-left", 
     minutesInputId : "minutes-left", 
     secondsInputId : "seconds-left", 
    }; 

    // Replace the default configuration if a custom config has been provided 
    if (typeof(customConfig) == "object") this.config = customConfig; 
} 

있다. 보시다시피 저는 새 Timer() 객체에 각 업데이트에서 호출해야하는 VisualTimer 함수를 주입하고 있습니다. 그러나 작동하지 않습니다. 등, 시작, 일시 정지, 정지 기능

function Timer(callbackObject, updateCallback, finishedCallback) { 

    // Define timer variables 
    this.state = Timer.stateStopped; 

    this.callbackObject = (typeof(callbackObject) == "object") ? callbackObject : null; 
    this.updateCallback = (typeof(updateCallback) == "function") ? updateCallback : null; 
    this.finishedCallback = (typeof(finishedCallback) == "function") ? finishedCallback : null; 

    this.hours = 0; 
    this.minutes = 0; 
    this.seconds = 0; 

    // Save the values that the timer was initially set to 
    this.startHours = 0; 
    this.startMinutes = 0; 
    this.startSeconds = 0; 

    /** 
    * Store the setInterval() ID that is created when the timer is started 
    * so that we can use this to clear it (stop the timer) later on. 
    */ 
    this.interval = null; 
} 

다음과 같이

타이머 "개체"는 정의하고 "생성자"에서 볼 수 있듯이 I는해야 콜백 함수를 주입하기위한 변수를 가질 각 틱

Timer.prototype.tick = function(fireCallback) { 
    fireCallback = (typeof(fireCallback) == "boolean") ? fireCallback : true; 

    if (this.seconds > 0) { 
     // If the seconds value is bigger than 0, subtract it by 1 
     this.seconds -= 1; 

     // Fire the update callback function 
     console.log(this.hours + ":" + this.minutes + ":" + this.seconds); 
     if (fireCallback && this.updateCallback != null) this.updateCallback.call(this.callbackObject, this.getCurrentValues()); 
    } 
    else if (this.minutes > 0) { 
     // If the seconds value is 0 but not the minutes value, subtract it by 1 
     this.minutes -= 1; 
     // And then also update the seconds value 
     this.seconds = 59; 

     // Fire the update callback function 
     console.log(this.hours + ":" + this.minutes + ":" + this.seconds); 
     if (fireCallback && this.updateCallback != null) this.updateCallback.call(this.callbackObject, this.getCurrentValues()); 
    } 
    else if (this.hours > 0) { 
     // If neither the seconds nor the minutes value is bigger than 0 but the hours value is, subtract it by 1 
     this.hours -= 1; 
     // And then also update the minutes and the seconds values 
     this.minutes = 59; 
     this.seconds = 59; 

     // Fire the update callback function 
     console.log(this.hours + ":" + this.minutes + ":" + this.seconds); 
     if (fireCallback && this.updateCallback != null) this.updateCallback.call(this.callbackObject, this.getCurrentValues()); 
    } 
    else { 
     // Stop the timer 
     this.stop(false); 

     // Fire the finished callback function 
     console.log("The timer has finished."); 
     if (fireCallback && this.finishedCallback != null) this.finishedCallback.call(this.callbackObject, this.getInitialValues()); 
    } 
}; 

똑딱 후 호출하는 것은 완벽하게 잘 작동, 그래서 거기 코드에서 잘못된 것은 지금까지 없다, 그리고을 console.log()를 타이머 때문에 제대로 출력하고 틱 기능이 완벽하게 작동합니다. 콜백 함수는 실행되지 않습니다.

많은 디버깅을 수행했으며 모든 함수가 완벽하게 작동하므로 문제가 주입 된 콜백 함수를 실제로 호출 할 수 있습니다. 다른 모든 것은 예상대로 작동합니다. 모든 코드 JSFiddle project으로 사용할 수 있습니다 :

이는 각 틱

VisualTimer.prototype.timerUpdated = function(timerData) { 
    if (typeof(timerData) == "object") 
    { 
     if (timerData.state == Timer.stateRunning) { 
      // Update the timer's display elements with new values 
      this.updateDisplayElements(timerData.hours, timerData.minutes, timerData.seconds); 
     } 
     else if (timerData.state == Timer.statePaused) { 
      // Make sure the correct values are displayed 
      this.updateDisplayElements(timerData.hours, timerData.minutes, timerData.seconds); 

      window.alert("The timer has been paused!"); 
     } 
     else if (timerData.state == Timer.stateStopped) { 
      // Reset the timer's input and display elements 
      this.updateDisplayElements(); 
      this.updateInputElements(); 

      window.alert("The timer has been stopped!"); 
     } 
    } 
}; 

UPDATE에 해고해야 updateCallback 기능입니다.

2 UPDATE :

문제 해결! 문제는 getInitialValues()이라고 명명 된 함수가 우연히 getCurrentValues()이라는 이름으로 호출되어 해당 함수를 덮어 썼기 때문에 state 속성이 콜백 함수로 보내지지 않은 것입니다. getInitialValues()은 상태를 보내지 않지만 getCurrentValues()은 상태를 보냅니다. 함수 이름을 수정 한 후 모두가 완벽하게 작동 :)

+0

모든 코드를 jsfiddle에 넣을 수 있습니까? – unobf

+0

@unobf http://jsfiddle.net/7c35b8qb/ – Tom

답변

1

당신은 제대로 콜백으로 타이머의 상태를 전달, 그렇게하지 않습니다 항상이 코드 번호 작전

VisualTimer.prototype.timerUpdated = function(timerData) { 
    if (typeof(timerData) == "object") 
    { 
     if (timerData.state == Timer.stateRunning) { // THIS IS ALWAYS FALSE 
      // Update the timer's display elements with new values 
      this.updateDisplayElements(timerData.hours, timerData.minutes, timerData.seconds); 
     } 
     else if (timerData.state == Timer.statePaused) { 
      // Make sure the correct values are displayed 
      this.updateDisplayElements(timerData.hours, timerData.minutes, timerData.seconds); 

      window.alert("The timer has been paused!"); 
     } 
     else if (timerData.state == Timer.stateStopped) { 
      // Reset the timer's input and display elements 
      this.updateDisplayElements(); 
      this.updateInputElements(); 

      window.alert("The timer has been stopped!"); 
     } 
    } 
}; 

사실이 있기 때문에 더 state 없다 재산 : timerData. 여기에 상태를 설정하는 곳이 있습니다. 이 시점에서 this 객체는 Timer 객체 자체

// Set the current state to running 
    this.state = Timer.stateRunning; 

위, 무 조작 코드를 호출 할 때 다음, 당신이 할 : thisstate 속성을 가지고 있지 않는 this.callbackObject에 설정

if (fireCallback && this.updateCallback != null) this.updateCallback.call(this.callbackObject, this.getCurrentValues()); 

.

콜백이 제대로 호출되지 않습니다.

+0

'Timer.prototype.getCurrentValues ​​= function() { return {상태 : this.state, 시간 : this.hours, 분 : this.minutes, 초 : this. 초}; }';는 상태를 통과하고 실제로 타이머가 시작됩니다. 입력에 2 분을 입력하고 시작을 클릭하면 입력 값이 거기에서 가져 와서 set() 함수 – Tom

+0

을 통해 Timer 객체에 삽입됩니다. 이것은 console.log() 출력에 의해 증명됩니다. 내가 테스트 한 기능에는 아무런 문제가 없습니다. 콜백이 실행되지 않거나 상태가 함수 내부에서 인식되지 않는 것입니다.하지만 전달 된대로 shouldnt 할 수없는 이유는 알 수 없습니다. 위의 함수를 사용합니다. – Tom

+0

오 마이 갓 ... 네 말이 맞아. 글쎄, 당신은 동시에 당신이 아니지만. 내가 코드를 리팩터링 할 때 실수로'getCurrentValues ​​()'와'getInitialValues ​​()'를 "getCurrentValues"로 이름을 바꾸었기 때문에 후자는 첫 번째를 덮어 썼고 그러므로 상태는 실제로는 timerUpdated() 함수로 보내지지 않았다. getInitialValues ​​()에서. 함수 이름을 고쳐서 이제는 완벽하게 작동합니다. – Tom

관련 문제