2013-03-11 7 views
2

다음 스크립트가 있습니다 (아래 참조). 그것에 관해 두 가지 질문이 있습니다 :KnockoutJS 관측 가능 기능

1. Knockoutjs의 맥락에서 다음과 같은 의미입니까?

$(document).ready(function() { 

    function ChatViewModel() { 

     var that = this; 

     that.userName = ko.observable(''); 
     that.chatContent = ko.observable(''); 
     that.message = ko.observable(''); 
     that.messageIndex = ko.observable(0); 
     that.activePollingXhr = ko.observable(null); 


     var keepPolling = false; 

     that.joinChat = function() { 
      if (that.userName().trim() != '') { 
       keepPolling = true; 
       pollForMessages(); 
      } 
     } 

     function pollForMessages() { 
      if (!keepPolling) { 
       return; 
      } 
      var form = $("#joinChatForm"); 


      that.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false, 
       success: function(messages) { 
        console.log(messages); 
        for (var i = 0; i < messages.length; i++) { 
         that.chatContent(that.chatContent() + messages[i] + "\n"); 
         that.messageIndex(that.messageIndex() + 1); 
        } 
       }, 
       error: function(xhr) { 
        if (xhr.statusText != "abort" && xhr.status != 503) { 
         resetUI(); 
         console.error("Unable to retrieve chat messages. Chat ended."); 
        } 
       }, 
       complete: pollForMessages 
      })); 
      $('#message').focus(); 
     } 

     that.postMessage = function() { 
      if (that.message().trim() != '') { 
       var form = $("#postMessageForm"); 
       $.ajax({url: form.attr("action"), type: "POST", 
        data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(), 
        error: function(xhr) { 
         console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText); 
        } 
       }); 
       that.message(''); 
      } 
     } 

     that.leaveChat = function() { 
      that.activePollingXhr(null); 
      resetUI(); 
      this.userName(''); 
     } 

     function resetUI() { 
      keepPolling = false; 
      that.activePollingXhr(null); 
      that.message(''); 
      that.messageIndex(0); 
      that.chatContent(''); 
     } 

    } 

    //Activate knockout.js 
    ko.applyBindings(new ChatViewModel()); 

}); 
+0

두 번째 질문에 대해 더 자세히 설명해 주시겠습니까? –

+0

나는'activePollingXhr'이 정의되어 있지 않거나 코드의 아무 곳에 나 구현되지 않았다는 것을 의미했습니다. 그렇다면 어떻게 호출 할 수 있습니까? – balteo

답변

3
  1. ko.observable(null);null의 값을 관찰 만든다. 값이 5ko.observable(5);과 다른 값은 없습니다.

  2. 나는 당신이 ajax 호출의 결과를 전달하여 관찰 할 수있는 that.activePollingXhr을 사용하고있는 것을 확인했다. 그러나이 호출은 비동기이며 $.ajax은 서버에서 가져온 데이터를 반환하지 않고 지연된 jquery를 반환합니다. that.activePollingXhr을 사용하여 success 콜백을 차단해야합니다. 여기가 코드를 같이하는 방법입니다 : 귀하의 질문에 아래의 코멘트에 관해서는

    $.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false, 
        success: function(messages) { 
         console.log(messages); 
         for (var i = 0; i < messages.length; i++) { 
          that.chatContent(that.chatContent() + messages[i] + "\n"); 
          that.messageIndex(that.messageIndex() + 1); 
         } 
         that.activePollingXhr(messages); // <-- Note where the call to activePollingXhr is 
        }, 
        error: function(xhr) { 
         if (xhr.statusText != "abort" && xhr.status != 503) { 
          resetUI(); 
          console.error("Unable to retrieve chat messages. Chat ended."); 
         } 
        }, 
        complete: pollForMessages 
    }); 
    

: that.activePollingXhrthat.activePollingXhr = ko.observable(null);로 정의 - null의 값을 관찰.

3

단지 null 등으로 관측을 초기화 : 여기

that.activePollingXhr(... 

전체 스크립트입니다

ko.observable(null); 

2.How 나는 기능은 아직 여기에로 정의되지 호출 할 수 있습니다 초기 값

관측 가능 함수를 호출해야하는 경우 두 번째 괄호 세트를 추가하기 만하면됩니다.

that.activePollingXhr()() 
관련 문제