< 이전 | 다음 >

학습 2: 사용자 정의 Dojo 위젯 작성

Dojo 툴킷에는 입력 필드, 콤보 상자 및 단일 선택 단추를 포함하여 수많은 표준 위젯이 포함됩니다. 재사용가능한 UI 요소 또는 일부 특정 기능을 캡슐화하기 위해 사용자 정의 위젯을 작성할 수도 있습니다. 이 학습에서 새로운 사용자 정의 Dojo 위젯을 작성합니다.

Dojo 위젯은 새 Dojo 위젯 마법사가 작성하는 세 개의 파일로 구성됩니다. 그런 다음 HTML 템플리트와 JavaScript 파일을 편집할 수 있습니다.
  1. 엔터프라이즈 탐색기 보기에서 WebContent/dojo 폴더를 마우스 오른쪽 단추로 클릭하고 새로 작성 > Dojo 위젯을 선택하십시오. 새로운 Dojo 위젯 마법사가 나타납니다.
  2. 모듈 이름 필드에서 loan을 입력하십시오.
  3. 위젯 이름 필드에서 LoanInput을 입력하십시오. 위젯 경로와 관련된 HTML 템플리트 및 스타일시트가 자동으로 채워집니다.
    새로운 Dojo 위젯 마법사
  4. 완료를 클릭하십시오. dojo/loan이라는 이름의 폴더에 3개의 파일이 작성됩니다.
    templates/LoanInput.html
    위젯에 대한 UI 템플리트.
    themes/LoanInput.css
    위젯에 스타일링을 제공합니다.
    LoanInput.js
    위젯의 비즈니스 로직 일부 및 JavaScript 백엔드를 제공합니다.
  5. 편집기에 위젯에 대한 LoanInput JavaScript 소스 파일이 열립니다.
  6. templateString 필드 아래에 계산 결과를 보관하는 데 사용될 세 개의 추가 필드(principal, interestPaidmonthlyPayment)를 추가하십시오. 이 필드의 기본값은 모두 0이어야 합니다. 각 필드 다음에 쉼표를 추가했는지 확인하십시오.
    templateString : dojo.cache("loan", "templates/LoanInput.html"),
    principal: 0,
    interestPaid: 0,
    monthlyPayment: 0,
  7. postCreate 기능 아래에 calculate라는 새 기능을 추가하십시오. postCreate 기능 뒤에 쉼표를 추가해야 합니다. 우선 새 calculate 기능을 비워 두십시오.
    	postMixInProperties : function() {
    },
    // this function will perform the calculations for our loan payment
    calculate: function() {
    }
  8. 엔터프라이즈 탐색기 보기에서 templates/LoanInput.html을 두 번 클릭하여 위젯에 대한 HTML 템플리트를 여십시오.
  9. 다음을 클릭하고 기본값을 승인하십시오. 완료를 클릭하십시오.
  10. 기존 div 내에서 세 개의 추가 하위 div 태그를 작성하십시오. <d를 입력하고 Ctrl+Space를 눌러 컨텐츠 지원을 사용할 수 있습니다. 팝업 창에서 <> div를 선택하여 태그를 삽입하십시오.
  11. 각 새 div 태그 내에서 텍스트 레이블(대출 금액:, 금리기간(년):)을 추가하십시오. 완료되면 코드가 다음과 유사해야 합니다.
    <div class="LoanInput">
    <div>Loan Amount: </div>
    <div>Interest Rate: </div>
    <div>Term (years): </div>
    </div>
  12. 이제 각각의 입력 필드에 대한 Dojo 위젯을 추가하십시오.
    1. 작업공간에서 적절한 탭을 클릭하여 팔레트를 표시하십시오. Dojo 위젯을 포함하는 여러 드로어가 표시되어야 합니다.
    2. 클릭하여 Dojo 양식 위젯 드로어를 펼치십시오.
      Dojo 양식 위젯 드로어
    3. CurrencyTextBox를 선택하고 div 태그 내의 대출 금액 레이블 옆에 놓으십시오.
    4. 새로 작성된 입력 요소 내에서 data-를 입력하고 컨텐츠 지원(Ctrl+Space)을 사용하여 속성 목록을 표시하십시오. data-dojo-props를 클릭하여 이를 삽입하십시오. Dojo 툴킷 SDK 1.7에서 시작하는 HTML5 표준을 수행하기 위해 속성이 data-dojo-props를 통해 기본적으로 설정됩니다.
    5. data-dojo-props 속성 내에서 cu를 입력하고 컨텐츠 지원(Ctrl+Space)을 사용하여 속성 목록을 표시하십시오. 통화를 클릭하여 삽입하십시오.
    6. 통화 속성 내에서 USD를 입력하십시오. 사용자 코드는 다음과 유사해야 합니다.
      <div>Loan Amount: <input type="text"
      				data-dojo-type="dijit.form.CurrencyTextBox"
      				data-dojo-props="currency: 'USD'">
      </div>
    7. 다음으로, 금리 필드에 대한 Dojo 위젯 마크업을 삽입하십시오. 레이블 뒤의 두 번째 div 태그 내에 커서를 두고 <input d>를 입력한 다음 커서를 d 옆에 놓고 컨텐츠 지원(Ctrl+Space)을 사용하여 속성 목록을 표시하십시오. data-dojo-type을 클릭하여 삽입하십시오.
    8. data-dojo-type 속성에서 사용 가능한 dojo 위젯 목록을 표시하도록 컨텐츠 지원을 호출하십시오. NumberSpinner가 표시될 때까지 dijit.form.N 입력을 시작하십시오. NumberSpinner를 클릭하여 페이지에 삽입하십시오.
    9. data-dojo-props 속성을 추가하십시오. 속성 내에서 쉼표로 분리되는 다음 특성을 설정하십시오.
      1. 값: 5
      2. smallDelta : .05
      3. intermediateChanges : true
      4. 제한조건 : {min: 0}
      컨텐츠 지원을 사용하여 위의 통화 속성을 추가한 것과 동일한 방법으로 이러한 특성을 삽입할 수 있습니다. 속성에 대한 특성 설정을 완료할 때, 사용자 코드는 다음과 유사해야 합니다.
      <div>Interest Rate: <input data-dojo-type="dijit.form.NumberSpinner"
      			data-dojo-props="value: 5, smallDelta:= 0.05, intermediateChanges: true, constraints: {min: 0}"> </input></div>
    10. 팔레트에서 ComboBox 위젯을 기간(년) div에 놓습니다.
    11. 일부 위젯에 대한 추가 구성은 팔레트(예: ComboBox)로부터 이를 놓을 때 사용 가능합니다. 삽입 콤보 상자 대화 상자에서 ComboBox에 대한 값을 추가할 수 있습니다. 1, 2, 3, 4, 5, 10, 15, 30에 대한 값을 추가하십시오.
    12. True로 설정하여 기본값으로 15를 설정하십시오. 확인을 클릭하십시오.
  13. 다음으로, data-dojo-attach-pointdata-dojo-attach-event 속성을 각각의 입력 위젯에 추가하십시오. data-dojo-attach-point 속성에 지정된 값은 위젯 인스턴스가 LoanInput.js 파일로부터 참조될 수 있는 이름입니다. data-dojo-attach-event 속성은 위젯에 이벤트 처리를 추가합니다.
    1. 컨텐츠 지원을 사용하여 data-dojo-attach-point 속성을 각 위젯에 추가하십시오. 각각 amount, rateterm으로 이름 지정하십시오.
    2. 각 위젯에 대해 data-dojo-attach-event="onChange: calculate"를 추가하십시오. onChange 이벤트가 이 위젯에서 발생할 때마다 LoanInput.js 파일에 추가하는 계산 함수를 호출합니다. LoanInput.html 파일의 최종 결과는 다음과 유사해야 합니다.
      <div class="LoanInput">
      <div>Loan Amount: <input type="text"
      data-dojo-type="dijit.form.CurrencyTextBox"
      data-dojo-props="currency: 'USD'"
      data-dojo-attach-point="amount"
      data-dojo-attach-event="onChange: calculate"></div>
      <div>Interest Rate: <input data-dojo-type="dijit.form.NumberSpinner"
      data-dojo-props="value:5,
      smallDelta:0.05,
      intermediateChanges:true,
      constraints:{min: 0}"
      data-dojo-attach-point="rate"
      data-dojo-attach-event="onChange: calculate">
      		</div>
      <div>Term (years): <select name="select"
      data-dojo-type="dijit.form.ComboBox"
      data-dojo-props="autocomplete:false"
      data-dojo-attach-point ="term"
      data-dojo-attach-event="onChange: calculate">
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>10</option>
      <option selected="selected">15</option>
      <option>30</option>
      </select>
      		</div>
      </div>
  14. LoanInput.html을 저장하고 닫은 다음 LoanInput.js를 다시 여십시오.
  15. html 파일에서 사용되는 세 개의 위젯에 대해 Dojo 모듈 종속 항목을 추가하십시오. 이러한 종속 항목은 페이지가 실행될 때 위젯을 작성하기 위한 필수 자원을 로드합니다. define 함수의 두 번째 인수는 종속 항목의 배열입니다. "dijit/_WidgetsInTemplateMixin", 종속성 바로 뒤에 쉼표로 구분된 다음 모듈 경로를 추가하십시오.
    1. "dijit/form/CurrencyTextBox"
    2. "dijit/form/NumberSpinner"
    3. "dijit/form/ComboBox"
    사용자 코드는 다음과 유사해야 합니다.
    define("loan/LoanInput",
    [ "dojo", "dijit", "dijit/_Widget",
    "dijit/_TemplatedMixin",
    		"dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
    "dijit/form/CurrencyTextBox",
    "dijit/form/NumberSpinner",
    "dijit/form/ComboBox",
    "dojo/text!loan/templates/LoanInput.html"
    ],
  16. 이제 단계 7에서 이전에 작성한 계산 함수에 대해 다음 코드를 추가하십시오. 원하면 컨텐츠 지원으로 실험할 수 있습니다. 표준 JavaScript 오브젝트(예: 수학 오브젝트)가 컨텐츠 지원에서 사용 가능하다는 것에 주목하십시오. 이전에 정의한 변수(principal, interestPaidmonthlyPayment)도 모두 사용 가능합니다.
    // this function will perform the calculations for our loan repayment
    	calculate: function() {
    		this.principal = this.amount.attr('value');
    		if(this.principal == NaN) {
    			this.monthlyPayment = 0;
    			this.principal = 0;
    			this.interestPaid = 0;
    			} else {
    			var interestRate = this.rate.attr('value') / 1200;
    			var termInMonths = this.term.attr('value') * 12;
    			
    			this.monthlyPayment = Math.pow(1 + interestRate, termInMonths) - 1;
    			this.monthlyPayment = interestRate + (interestRate / this.monthlyPayment);
    			this.monthlyPayment = this.monthlyPayment * this.principal;
    			
    			this.interestPaid = (this.monthlyPayment * termInMonths) - this.principal;
    		}
    }
    계산 함수는 대출의 프린시펄을 저장하고 매월 납부를 계산하며 지불된 이자를 계산합니다.
  17. 사용자 정의 위젯을 구성하는 모든 파일을 저장하고 닫으십시오.
LoanInput.js는 다음과 유사해야 합니다.
define("loan/LoanInput", [ "dojo", "dijit", "dijit/_Widget",
		"dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin", "dijit/form/CurrencyTextBox", "dijit/form/NumberSpinner", "dijit/form/ComboBox",
		"dojo/text!loan/templates/LoanInput.html" ], function(dojo, dijit,
		_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, CurrencyTextBox, NumberSpinner, ComboBox) {
	dojo.declare("loan.LoanInput", [ dijit._Widget, dijit._TemplatedMixin,
			dijit._WidgetsInTemplateMixin ], {
	// Path to the template
		templateString : dojo.cache("loan", "templates/LoanInput.html"),
		principal: 0,
		interestPaid: 0,
		monthlyPayment: 0,

		// Override this method to perform custom behavior during dijit construction.
	// Common operations for constructor:
	// 1) Initialize non-primitive types (i.e. objects and arrays)
		// 2) Add additional properties needed by succeeding lifecycle methods
	getRating : function(){
			
		},

		// When this method is called, all variables inherited from superclasses are 'mixed in'.
	// Common operations for postMixInProperties
		// 1) Modify or assign values for widget property variables defined in the template HTML file
	getRating : function(){
		},

				// postCreate() is called after buildRendering(). This is useful to override when 
		// you need to access and/or manipulate DOM nodes included with your widget.
		// DOM nodes and widgets with the dojoAttachPoint attribute specified can now be directly
	// accessed as fields on "this". 
	// Common operations for postCreate
		// 1) Access and manipulate DOM nodes created in buildRendering()
	// 2) Add new DOM nodes or widgets 
	getRating : function(){
		},
		//this function will perform the calculations for our loan payment
		calculate: function() {
			this.principal = this.amount.attr('value');
			if(this.principal == NaN) {
				this.monthlyPayment = 0;
				this.principal = 0;
				this.interestPaid = 0;
			} else {
				var interestRate = this.rate.attr('value') / 1200;
				var termInMonths = this.term.attr('value') * 12;
				
				this.monthlyPayment = Math.pow(1 + interestRate, termInMonths) - 1;
				this.monthlyPayment = interestRate + (interestRate / this.monthlyPayment);
				this.monthlyPayment = this.monthlyPayment * this.principal;
				
				this.interestPaid = (this.monthlyPayment * termInMonths) - this.principal;
			}
}
	});
});

학습 체크포인트

사용자 정의 Dojo 위젯을 작성했습니다.

학습한 내용은 다음과 같습니다.
  • 컨텐츠 지원 및 템플리트를 사용하여 Dojo 코드를 빠르게 작성하는 방법
  • 사용자 정의 Dojo 위젯의 HTML 템플리트를 수정하는 방법
  • 사용자 정의 Dojo 위젯의 JavaScript 파일을 수정하는 방법
< 이전 | 다음 >
주제 유형을 표시하는 아이콘 학습서 학습 주제
Information Center의 이용 약관 | 피드백

시간소인 아이콘 마지막 업데이트 날짜: 2014-05-22

파일 이름: loan_lesson2.html