2010-12-09 7 views
3

knockoutjs으로 조금 놀았으며 자바 스크립트에서 이러한 뷰 모델을 작성하여 훨씬 간단하고 선언적 방식으로 볼 수 있도록 다음 예제를 충분히 만들었습니다. 즉 처음에는 을 정의합니다. 당신은을 관찰하고, data-bind 속성은 을 정의합니다. 특정 방식으로 뷰 모델이 변경 될 때 수행 할 작업을 정의하십시오.KnockoutJS를 사용하여 AJAX를 통해 서버의 데이터를 관찰하는 방법은 무엇입니까?

하지만이 모든 것은 클라이언트에서만 발생합니다.

knockoutjs를 사용하여 서버의 객체 상태를 관찰하려면 어떻게해야합니까? AJAX 통화를 통해?

있는 index.htm :

<!doctype html> 
<html> 
    <title>Knockout example</title> 
    <head> 
     <script type="text/javascript" src="js/knockout-1.1.1.debug.js"></script> 
     <script type="text/javascript" src="js/main.js"></script> 
     <link rel="stylesheet" href="css/main.css" type="text/css"/> 
    </head> 
    <body> 

     <!-- FIRST AREA --> 
     <div class="infobox"> 
      <div data-bind="visible: noNamesFilled"> 
       <p>This is an example with NO names filled.</p> 
      </div> 
      <div data-bind="visible: bothNamesFilled"> 
       <p>This is an example with both names filled.</p> 
      </div> 
      <div data-bind="visible: firstNameOnlyFilled"> 
       <p>This is an example with only the first name filled.</p> 
      </div> 
      <div data-bind="visible: lastNameOnlyFilled"> 
       <p>This is an example with the last name filled but not the first name</p> 
      </div> 
     </div> 

     <!-- SECOND AREA --> 
     <p>First name: <input data-bind="value: firstName, valueUpdate:'afterkeydown'" /></p> 
     <p>Last name: <input data-bind="value: lastName, valueUpdate:'afterkeydown'" /></p> 
     <div data-bind="visible: bothNamesFilled"> 
      <h2 class="normal">Hello, <span data-bind="text: fullName"></span>.</h2> 
     </div> 
     <div data-bind="visible: firstNameOnlyFilled"> 
      <h2 class="informal">Hi there <span data-bind="text: fullName"></span>!</h2> 
     </div> 
     <div data-bind="visible: lastNameOnlyFilled"> 
      <h2 class="formal">Hello, Mr. <span data-bind="text: fullName"></span>.</h2> 
     </div> 

     <!-- THIRD AREA --> 
     <div data-bind="visible: noNamesFilled"> 
      <p><span class="bad">:-(</span> Please fill in both names.</p> 
     </div> 
     <div data-bind="visible: bothNamesFilled"> 
      <p><span class="good">:-)</span> Good job, both names are filled!</p> 
     </div> 
     <div data-bind="visible: firstNameOnlyFilled"> 
      <p><span class="ok">:-(</span> Please fill in the last name, too.</p> 
     </div> 
     <div data-bind="visible: lastNameOnlyFilled"> 
      <p><span class="ko">:-(</span> Please fill in the first name as well.</p> 
     </div> 
    </body> 
</html> 

main.css가 :

* { margin: 0; padding: 0} 
body { margin: 10px} 
p { margin: 10px} 
.infobox { 
    background-color: #eee; 
    width: 300px; 
    height: 100px; 
    padding: 10px; 
} 
.informal { 
    color: purple; 
    font-family: arial; 
} 
.normal { 
    color: black; 
    font-family: new courier; 
} 
.formal { 
    color: black; 
    font-size: 11pt; 
    font-family: times roman; 
    background-color: #eee; 
} 
.good { 
    width: 20px; 
    background-color: lightgreen; 
} 
.ok { 
    width: 20px; 
    background-color: yellow; 
} 
.bad { 
    width: 20px; 
    background-color: tomato; 
} 

main.js :

window.onload= function() { 

    var viewModel = { 
     firstName : ko.observable(''), 
     lastName : ko.observable('') 
    }; 
    viewModel.fullName = ko.dependentObservable(function() { 
     return viewModel.firstName() + " " + viewModel.lastName(); 
    }); 

    viewModel.bothNamesFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length > 0 && viewModel.lastName().length > 0; 
    }, this); 
    viewModel.firstNameOnlyFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length > 0 && viewModel.lastName().length == 0; 
    }, this); 
    viewModel.lastNameOnlyFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length == 0 && viewModel.lastName().length > 0; 
    }, this); 
    viewModel.noNamesFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length == 0 && viewModel.lastName().length == 0; 
    }, this); 

    ko.applyBindings(viewModel); 
} 

답변

4

setTimeout을 사용하여 JQuery를 사용하여 $ .ajax 호출을하는 함수를 호출합니다. JSON 데이터를 반환하면 해당 데이터를 뷰 모델로 설정하고 마지막으로 setTimeout을 다시 호출하여 함수를 호출합니다.

0

다음은 주로 main.js를 업데이트하여 JQuery와 함께 ajax 호출을 수행하는 업데이트 된 예제입니다.

HTML 파일에는 1 대신 Knockout 3이 포함됩니다. HTML에는 JQuery 기능이 작동하도록 최신 JQuery가 포함되어 있습니다.

js/server_data.js가 있으므로 유효한 json 데이터가 있습니다. $ .ajax 설정에서 url을 가지고있는 서버 측 스크립트로 바꿀 수 있지만 해당 내용 유형을 application/json으로 설정하십시오. 예를 들어, PHP 스크립트는 Content-type 헤더를 다음과 같이 설정할 수 있습니다. header ('Content-type : application/json'); JSON 형식으로 데이터를 인쇄하기 전에.

새로운 main.html :

<!doctype html> 
<html> 
    <title>Knockout example</title> 
    <head> 
     <script type="text/javascript" src="js/knockout-3.0.0.debug.js"></script> 
     <script src="http://code.jquery.com/jquery-latest.min.js"></script> 
     <script type="text/javascript" src="js/main.js"></script> 
     <link rel="stylesheet" href="css/main.css" type="text/css"/> 
    </head> 
    <body> 

     <!-- FIRST AREA --> 
     <div class="infobox"> 
      <div data-bind="visible: noNamesFilled"> 
       <p>This is an example with NO names filled.</p> 
      </div> 
      <div data-bind="visible: bothNamesFilled"> 
       <p>This is an example with both names filled.</p> 
      </div> 
      <div data-bind="visible: firstNameOnlyFilled"> 
       <p>This is an example with only the first name filled.</p> 
      </div> 
      <div data-bind="visible: lastNameOnlyFilled"> 
       <p>This is an example with the last name filled but not the first name</p> 
      </div> 
     </div> 

     <!-- SECOND AREA --> 
     <p>First name: <input data-bind="value: firstName, valueUpdate:'afterkeydown'" /></p> 
     <p>Last name: <input data-bind="value: lastName, valueUpdate:'afterkeydown'" /></p> 
     <div data-bind="visible: bothNamesFilled"> 
      <h2 class="normal">Hello, <span data-bind="text: fullName"></span>.</h2> 
     </div> 
     <div data-bind="visible: firstNameOnlyFilled"> 
      <h2 class="informal">Hi there <span data-bind="text: fullName"></span>!</h2> 
     </div> 
     <div data-bind="visible: lastNameOnlyFilled"> 
      <h2 class="formal">Hello, Mr. <span data-bind="text: fullName"></span>.</h2> 
     </div> 

     <!-- THIRD AREA --> 
     <div data-bind="visible: noNamesFilled"> 
      <p><span class="bad">:-(</span> Please fill in both names.</p> 
     </div> 
     <div data-bind="visible: bothNamesFilled"> 
      <p><span class="good">:-)</span> Good job, both names are filled!</p> 
     </div> 
     <div data-bind="visible: firstNameOnlyFilled"> 
      <p><span class="ok">:-(</span> Please fill in the last name, too.</p> 
     </div> 
     <div data-bind="visible: lastNameOnlyFilled"> 
      <p><span class="ko">:-(</span> Please fill in the first name as well.</p> 
     </div> 
    </body> 
</html> 

JS/main.js :

$(document).ready(function() { 

    var viewModel = { 
     firstName : ko.observable(''), 
     lastName : ko.observable('') 
    }; 
    viewModel.fullName = ko.dependentObservable(function() { 
     return viewModel.firstName() + " " + viewModel.lastName(); 
    }); 

    viewModel.bothNamesFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length > 0 && viewModel.lastName().length > 0; 
    }, this); 
    viewModel.firstNameOnlyFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length > 0 && viewModel.lastName().length == 0; 
    }, this); 
    viewModel.lastNameOnlyFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length == 0 && viewModel.lastName().length > 0; 
    }, this); 
    viewModel.noNamesFilled = ko.dependentObservable(function() { 
     return viewModel.firstName().length == 0 && viewModel.lastName().length == 0; 
    }, this); 

    ko.applyBindings(viewModel); 

    // send request to the server to download the server's model information. 
    $.ajax(
    { 
     'url': 'js/server_data.js', 
     'dataType': 'json', 
     'method': 'post', 
     'error': function(jqXHR, textStatus, errorThrown) 
     { 
      // error callback in case you play with this code and run into trouble. 
      alert('There was a problem handling the ajax request. The error information is: jqXHR: ' 
      +jqXHR+", textStatus: "+textStatus+", errorThrown: "+errorThrown); 
     }, 
     'success': function(data) 
     { 
      // when it is downloaded and parsed to create the "data" parameter, update the viewModel. 
      viewModel.firstName(data.firstName); 
      viewModel.lastName(data.lastName); 
     } 
    } 
    ); 
} 
); 

JS/데이터베이스에서 할 수있는 동적으로 생성 된 데이터를 나타내는 server_data.js :

{ 
    "firstName": "John", 
    "lastName": "Doe" 
} 

jsteve는 올바른 생각을 갖고 있지만 페이지로드시 데이터를 다운로드하려는 경우 setTimeout을 사용하지 마십시오. 에스. 대신, JQuery의 문서 준비 콜백과 JQuery의 Ajax 성공 콜백을 사용하면 원하는 때에 정확하게 실행될 수있다.

서버의 데이터 변경 내용을 지속적으로 수신하고 응답하려면 긴 폴러 기법을 살펴보십시오. 긴 폴러는 서버에 대한 빈번한 새 요청을 요구하는 바쁜 대기보다 효율적이고 정확하게 시간을 측정합니다.