티스토리 뷰

Visual Studio에서 JavaScript 응용프로그램 개발하기


Before delving into the details of the application, I want to say a few things about JavaScript application development. One of the challenges facing the JavaScript developer is the dynamic nature of the language. With JavaScript you aren’t constrained by a rigid type system; instead, objects can be built dynamically. This poses a challenge to the developers of JavaScript editors and IDEs. With strongly typed languages such as C# and Java, the type information can be used to provide enhanced code navigation, refactoring and IntelliSense. With JavaScript, on the other hand, the lack of type information means that the IDE typically provides far fewer developer aids.
응용프로그램의 자세한 사항으로 들어가기 앞서, 저는 JavaScript 응용프로그램 개발에 대하여 몇 가지 이야기 하고 싶습니다. 훌륭한 JavaScript 개발자로 도전할만 한 것은 언어의 역동적 성질입니다. JavaScript와 함꼐라면 딱딱한 유형의 시스템으로 부터 구애받지 않을 수 있습니다; 그 대신에, 객체를 역동적으로 만들 수 있습니다. JavaScript 에디터와 통합개발툴(IDE) 개발자들의 도전 자세가 
C#또는 Java와 같은 강력한 유형의 언어와 같이 강력한 Refactoring 또는 IntelliSense한 안내 코드를 제공하여 사용할 수 있게합니다. 그러나 반대로 자바스크립트는 유형 정보의 뜻이 몇몇 개발자를 보조하는보통의 IDE에서 부족하게 제공되고있습니다.


Fortunately, things have improved recently, with Visual Studio 2010 performing pseudo-execution of your JavaScript code in order to determine the “shape” of each object, allowing it to provide JavaScript IntelliSense. In order to take full advantage of the IntelliSense support, we have to provide the IDE with a few “hints” in the form of “references” that tell the IDE which files to include in its pseudo-execution. With the demo project, all files start with a reference comment that tells the IDE to include the intellisense.js file. The content of this file is simply a list of references that ensure the IDE includes all the important application JavaScript files, providing quality IntelliSense support across the application, as shown here:
다행히도, 이런 것들은 비쥬얼 스튜디오 2010의 JavaScript IntelliSense 에서 제공된 각각의 JavaScript 객체의 "형"(Shape)을 측정하는 JavsScript 가상시현(pseudo-execution) 기능으로  현제 많이 개선되었습니다. IntelliSense의 모든 장점을 취하기 위해선 가상시현(pseudo-execution)을 위해 IDE 파일 내부에 몇가지 힌트를 참조양식(Form of "references")과  함께 제공해야했습니다. 시현(Demo) 프로젝트에는 모든 파일의 시작에 intelllisense.js파일을 포함하는 IDE 참조코멘트(Reference comment)가 있습니다. 다음에 보시는 크로스 응용프로그램을 지원하는 IntellliSense  파일의 내용은 IDE에서 포함한 중요한 응용프로그램 JavaScript파일들의 간단한 참조리스트입니다:



  1. /// Ensure IntelliSense includes all the files from this project.
  2. ///
  3. /// <reference path="app.js" />
  4. /// <reference path="viewModel/ApplicationViewModel.js" />
  5. /// <reference path="viewModel/SearchResultsViewModel.js" />
  6. /// <reference path="viewModel/TweetViewModel.js" />
  7. /// <reference path="viewModel/TwitterSearchViewModel.js" />
  8. /// <reference path="lib/jquery-1.6.4.js" />
  9. /// <reference path="lib/cordova-1.5.0.js" />
  10. /// <reference path="lib/knockout-1.2.1.js" />

JavaScript is a relaxed and forgiving language, with features such as value coercion and semi­colon insertion making it easy to use in a scripting environment. However, these same features often become problematic when managing large quantities of code. For that reason I highly recommend using JSLint, a tool that applies a more rigid set of coding standards to JavaScript. A popular Visual Studio Extension adds JSLint support (jslint4vs2010.codeplex.com), reporting lint errors within the error console. I’ve used JSLint for the Twitter Search application (and virtually every other JavaScript project I’ve worked on).
JavaScript는 느슨하고 관용적인 언어이지만, 스크립팅 환경에서 값의 강제성과 세미콜론(;)을 쉽게 삽입하는 특징을 이루고 있습니다. 그러나 이 것과 같은 특징들은 큰 규모의 코드를 관리하는데 있어 자주 문제시 되어지는 부분입니다. 그런 이유에서 저는 
툴에 더욱 완고한 표준 JavaScript 코딩을 설정 적용하고 싶다면, 강하게 JSLint를 사용할 것을 권하고 싶습니다. 대부분의 Visual Studio Extension 에는 JSLint 지원(jslint4vs2010.codeplex.com)하여 lint 오류를 오류콘솔을 통해서 통보하고 있습니다. 저는 트위터 검색 응용프로그램에 JSLint를 사용하였습니다(그리고 가상적으로 모든 JavaScript 프로젝트에 사용하고 있습니다).


You might notice a “globals” comment at the start of each JavaScript file within the project. JSLint helps prevent variables “leaking” into global scope by accidental omission of the var keyword. The “globals” comment provides JSLint with a formal definition of which variables are allowed to occupy a global scope.
당신은 프로젝트의 JavaScript파일에 "global"이라는 코멘트를 주의하셔야 할 것입니다. JSLint는 우발적인 키워드 생략으로 인한 전역적으로 발생하는 일명 "누수"현상을 막아줍니다. "global" 코멘트는 선점적으로 정의하여 제공하고 있습니다.


Model-View-View Model(MVVM) 응용프로그램 구조

The Twitter Search application is, from the perspective of the phone’s browser control, a single-page application. Conversely, from the user perspective, it has multiple pages, as seen in Figure 5. In order to support this, a Knockout ViewModel is constructed that contains a stack of ViewModel instances, each one representing a page within the application. As the user navigates to a new page, the corresponding ViewModel is added to this stack, and when the user navigates back, the topmost ViewModel is popped off the stack (see Figure 6).
트위터 검색 응용프로그램은 폰(phone)의 브라우저 컨트롤러로 보는 단일 
페이지 응용프로그램입니다. 반대로 사용자 시점에서 보면 Figure 5에서 보듯 다중 페이지로 보입니다. 응용프로그램간 페이지를 각각 대표하는 ViewModel 객체들의 더미(stack)을 포함하도록 지원하는 Knockout ViewModel이 구성되어졌습니다. 사용자에게 새로운 페이지를 안내하게 된다면 이에 상응하는 ViewModel을 ViewModel객체들의-더미(stack)에 추가하고 사용자에게 안내를 돌려주게 되고 가장 상위의 ViewModel은 ViewModel객체 더미에서 튀어나오게 됩니다(참조 Figure 6).


Figure 6 The Knockout ApplicationViewModel

  1. /// <reference path="..//intellisense.js" />
  2. /*globals ko*/
  3. function ApplicationViewModel() {
  4.   /// <summary>
  5.   /// The ViewModel that manages the ViewModel back-stack.
  6.   /// </summary>
  7.   // --- properties
  8.   this.viewModelBackStack = ko.observableArray();
  9.   // --- functions
  10.   this.navigateTo = function (viewModel) {
  11.     this.viewModelBackStack.push(viewModel);
  12.   };
  13.   this.back = function () {
  14.     this.viewModelBackStack.pop();
  15.   };
  16.   this.templateSelector = function (viewModel) {
  17.     return viewModel.template;
  18.   }
  19. }


When the application starts, an instance of the ApplicationViewModel is created and bound to the UI using Knockout:
응용프로그램이 시작되면 응용프로그램의 ViewModel의 객체가 생성 및 Knockout을 이용한 UI로 묶여지게 됩니다:


  1. document.addEventListener("deviceready", initializeViewModel, false);
  2. var application;
  3. function initializeViewModel() {
  4.   application = new ApplicationViewModel();
  5.   ko.applyBindings(application);
  6. }



The UI itself is quite simple, comprising a div element that uses the Knockout template binding to render the ViewModel stack:
div 엘레멘트를 포함한 Knockout 템플릿의 묶음과 
ViewModel 더미를 표현하는 UI 자체는 굉장히 단순합니다:



  1. <body>
  2.   <h1>Cordova Twitter Search</h1>
  3.   <div class="app" data-bind ="template: {name: templateSelector, foreach: viewModelBackStack}">
  4.   </div>
  5. </body>


The Knockout template binding works in a similar manner to the Silverlight ItemsControl in that it binds to an array of ViewModel instances and is responsible for generating the View for each via a template. In this case, the templateSelector function is invoked on the ApplicationViewModel in order to determine the named template for each ViewModel.
Knockout 템플릿 바인딩은 
SilverLight ItemControl의 템플릿을 통한 각각의 VIew를 생성하는 역활과 ViewModel 객체의 배열로 묶어주는 방식과 비슷하게 동작합니다. 이 경우에 각각의 ViewModel의 이름을 지정하기 위한 ApplicationViewModel을 templateSelector  가 호출하게됩니다.


If you run this application you’ll find that it doesn’t actually do anything—that’s because there aren’t any ViewModels to represent the pages of the application!
이응용프로그램을 실행하면 막상 아무 것도 하고 있지 않을 것을 발견할 것입니다. 왜냐하면 응용프로그램을 대표하는 페이지지 즉 ViewModel들이 어디에도 없기 때문입니다!


트위터 검색 뷰 모델(The TwitterSearchViewModel)

I’ll introduce the first ViewModel, TwitterSearchViewModel, which represents the first page of the application. This ViewModel exposes a few simple observable properties that support the UI, namely the searchTerm, which is bound to the user input field, and isSearching, which is a Boolean observable that disables the search button when the Twitter APIs are being queried via HTTP. It also exposes a search function that’s bound to the search button, in much the same way that you would bind an ICommand to a Button within Silverlight (see Figure 7).
제가 응용프로그램을 대표하는 첫 페이지 첫 ViewModel인 TwitterSearchViewModel을 소개하겠습니다. 이 ViewModel은 몇 가지 간단한 관찰가능한 UI요소들인 사용자 입력 필드(field)인 searchTerm과 Twitter API로 
HTTP를 통하여 질의할 때 조회 버튼이 사용불가능 하도록하는 Boolean 관찰자인 isSearching으로 나타내보여집니다. Silverlight에서 ICommand버튼에 바인드 하듯이, 이 것 역시 조회 기능을 조회버튼에 바인드 할 수 있습니다(참조 Figure 7).


Figure 7 The TwitterSearchViewModel

  1. /// <reference path="..//intellisense.js" />
  2. /*globals $ application ko localStorage SearchResultsViewModel TweetViewModel*/
  3. function TwitterSearchViewModel() {
  4.   /// <summary>
  5.   /// A ViewModel for searching Twitter for a given term.
  6.   /// </summary>
  7.   // --- properties
  8.   this.template = "twitterSearchView";
  9.   this.isSearching = ko.observable(false);
  10.   this.searchTerm = ko.observable("");
  11.   // --- public functions
  12.   this.search = function () {
  13.     /// <summary>
  14.     /// Searches Twitter for the current search term.
  15.     /// </summary>
  16.     // implementation detailed later in this article ...
  17.   };
  18. }


The template property of the ViewModel names the View that’s associated with this ViewModel. This View is described as a jQuery template within the index.html file:
ViewModel 템플릿 요소인 View를 ViewModel의 조합으로 이름하였습니다. 이 VIew는 index.html파일에 jQuery템블릿으로 기술되어진 것입니다:


  1. <script type=text/x-jquery-tmpl" charset="utf-8" id="twitterSearchView" 
  2.   <div>
  3.     <form data-bind="submit: search">
  4.       <input type="text"
  5.         data-bind="value: searchTerm, valueUpdate: 'afterkeydown'" />
  6.       <button type="submit"
  7.         data-bind="enable: searchTerm().length > 0 &&
  8.           isSearching() == false">Go</button> 
  9.     </form>     
  10.   </div>
  11. </script>



If you add an instance of the TwitterSearchViewModel to the application ViewModel stack, the application now shows the first page, as shown in Figure 8.
만약 TwitterSearchViewModel의 객체를 응용프로그램 ViewModel 더미(stack)에 추가했다면 Figure 8에서 보듯이 으용프로그램은 첫페이지를 보여주게 됩니다.



The TwitterSearchViewModel Rendered via the twitterSearchView Template
Figure 8 twitterSearchView템플릿을 통한 TwitterSearchViewModel 표현

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함