2014-06-16 2 views
0

bind()을 사용하여 내부 기능 중 하나에서 올바른 컨텍스트를 가져올 수 없습니다. 여기 내 코드는 다음과 같습니다약속을 사용하여 bind()에 올바른 컨텍스트를 가져올 수 없습니다.

return { 
    /** 
    * Checks if the table loader is active 
    * @return {home} Returns this module for chaining 
    */ 
    loadStatusLog: function() { 
     if ($("#status-log-box").length) { 
      $.getJSON("/Home/CurrentEvents", function(json, status, xhr) { 
       if (status === "error") { 
        var errmsg = "Sorry but there was an error: "; 
        $("#result-msg").html(errmsg + xhr.status + " " + xhr.statusText); 
       } 
       else if (status === "success") { 
        if (json.globalGenerationStatus) { 
         console.log(this); 
         this.updateProgressInterval = setInterval(this.updateGenerationProgress, 1000); 
        } 
        var html = statusLog(json); 
        $("#status-log-table").html(html); 
       } 
      }.bind(this)); 
     } 
     return this; 
    }, 
    /** 
    * Looks at the generation progress file and updates the progress bar for a running event 
    * @returns {home} Returns this module for chaining 
    */ 
    updateGenerationProgress: function() { 
     var runningEvent = $(".running-event"); 
     $.ajax({ 
      type: "POST", 
      url: "/Home/readGenerationStatusFile", 
      global: false 
     }).done(function(data) { 
      runningEvent.css("width", data + "%").attr("aria-valuenow", data); 
      if (data === "100") { 
       console.log(this); 
       clearInterval(this.updateProgressInterval); 
       $("span", runningEvent).text("Complete").parent().removeClass("running-event").parent().removeClass("active progress-striped"); 
      } 
     }.bind(this)); 
     return this; 
    } 

}; 

내 주요 목표는 updateGenerationProgress() 기능에서 loadStatusLog() 기능의 내부 설정 간격을 취소하는 것입니다. console.log() 문 내부에 이 올바른 컨텍스트 (이 개체)를 출력하지만 console.log() 문 내부에 updateGenerationProgress()은 컨텍스트로 Window를 출력합니다. 왜 이런거야? 약속과 상황에 대해 내가 빠뜨린 것이 있습니까?

답변

1

당신은, 상황에 맞는 엄격한 모드에서 비 엄격 모드와 undefinedwindow (또는 근로자)에이 설정됩니다 너무

this.updateProgressInterval = 
    setInterval(this.updateGenerationProgress.bind(this), 1000); 

그렇지 않으면 간격 컨텍스트를 설정해야합니다.

+0

와우, 나는 그것을 간과했다고 믿을 수 없다. 정말 고맙습니다! 그것은 모든 것을 해결했습니다. – Aaron

+1

@Aaron 개인적으로 DOM을 업데이트하는 논리에서 서버에서 물건을 가져 오는 논리를 개인적으로 분리 할 수있어서 기쁘다. –

관련 문제