본문 바로가기
개발/dart

3. Add Elements to the DOM

by 허허 그림 2014. 3. 2.
728x90

* 전체 링크

1.get started

2. Connect Dart & HTML

3. Add Elements to the DOM

4, Remove DOM Elements

- 5. Install Shared Packages

6. Define a Custom Element

7. Use Future-Based APIS

8. Use Streams for Data

9. Fetch Data Dynamically

10. Get Input from a Form

11. Use Indexed DB

12. Write Command-line Apps


Add Elements to the DOM
DOM에 요소 추가하기.

Dynamically add items to the browser page.
동적으로 브라우저 페이지에 아이템 추가하기.

As you learned in the previous tutorial, the DOM represents the structure of a web page document using a simple tree structure. Each node in the tree represents an item on the page. Each node in the tree keeps track of both its parent and its children. In Dart, the Node class contains the methods and properties that implement a node’s tree functionality.

이전 튜토리얼에서 배운대로, DOM은 간단한 트리 구조를 이용해서 웹 페이지의 구조를 나타냅니다. 트리에서 각각의 노드는 페이지에서의 아이템을 나타냅니다. 또 트리에서 각각의 노드는 부모와 자식 둘다의 끈을 가지고 있습니다. Dart에서, Node 클래스는 노드의 트리의 기능을 구현한 함수와 속성이 포함되어 있습니다.

HTML page elements are one kind of node that can be in the DOM tree. They have a rectangular area on the page and can receive events. Examples of elements include heading elements, paragraph elements, table elements, button elements, and so on.

HTML 페이지 요소는 DOM트리 안에 있을 수 있는 노드의 한 종류입니다. 그것들은 페이지에 있는 사각형 영역이고 이벤트를 받을 수 있습니다. 그러한 요소들의 예로는 head 요소, 단락 요소, 테이블 요소, 버튼 요소 등이 있습니다.

In Dart, elements are implemented by the Element class, which is a subclass of Node. Because the nodes you care about most are usually elements, this tutorial focuses on Element, rather than on Node.

Dart 에서, 요소들은 Node 클래스의 하위 클래스인 Element 클래스에 의해서 구현되어집니다. 당신이 가장 관심있어하는 노드는 일반적으로 요소(element)이기 때문에, 이번 튜토리얼에서는 노드보다는 요소에 더 초점을 맞추겠습니다.



Copy and run the todo app
todo 앱을 카피하고 실행하기.

In this tutorial, you will be working with a sample web app that is a partial implementation of a todo list. This program dynamically changes the DOM, and therefore the web page, by adding elements to the DOM tree.

이번 튜토리얼에서는 , 당신은 할일 목록 앱의 일부 기능을 구현하는 간단한 웹 앱을 만들것입니다. 이 프로그램은 DOM 트리에 요소를 추가함으로 동적으로 DOM을 바꿉니다.

Try it! Type in the text field and press return. The app adds an item to the list. Enter a few items into the input field:

시도해 보세요! 텍스트 필드에 입력을 하고 엔터키를 누르세요. 그러면 앱은 리스트에 아이템을 추가합니다. 입력란에 몇 개의 아이템을 넣으세요.


This is the beginning of an app to manage a list of things to do. Right now, this app is for procrastinators only because the program can only add items to your to do list but not remove them.

이것은 해야 할 일들의 리스트를 관리해주는 앱의 시작단계입니다. 지금은, 이 앱이  해야 할 일은 추가할 수 있지만 삭제는 할 수 없는 조금은 덜 된 앱입니다.

About parent and child Elements in Dart
Dart에서 부모와 자식 요소에 대해서

The Node class in Dart implements the basic treeing behavior for nodes in the Dart DOM. The Element class is a subclass of Node that implements the behavior specific to page element nodes. For example, an element knows the width and height of its enclosing rectangle on the page and it can receive events.

Dart에서 Node 클래스는 Dart DOM의 노드에 대해서 기본적인 트리 작동방법만이 구현되어 있습니다. 이 Element 클래스는  페이지 요소 노드에 고유한 동작을 구현한 Node 클래스의 하위 클래스입니다. 예를 들면, 일반적인 요소는  페이지안에서 자기의 높이와 넓이를 알고 있고 이벤트를 수신할 수 있습니다.

You can manipulate the DOM tree by adding and deleting nodes. However, many Dart apps are concerned only with page elements. So for convenience and code simplicity, the Element class implements API for interacting with a subset of the DOM that includes only the nodes that are Elements. You can work with a virtual tree of Elements rather than the more complex tree of Nodes. This tutorial shows you how to manipulate the DOM through the Element class.

당신은 DOM 트리를 추가하고 삭제하는 등의 조작을 할 수 있습니다. 그러나 많은 Dart 앱들은 단지 페이지 요소에만 관심을 가졌습니다. 그래서 편리함과 코드의 간결성을 위해서, Element 클래스는 요소들이라고 하는 노드만을 포함하는 DOM의 일부와 상호작용을 하기 위한 API를 구현합니다. 당신은 노드의 복잡한 트리 구조보다는 요소의 가상트리구조로 작업을 할 수 있습니다. 이 번 튜토리얼은 당신이 Element 클래스를 가지고 어떻게 DOM을 조작하는지를 알려 줄 것입니다.

An Element has a parent Element and maintains references to its child Elements in a list.

요소는 리스트 상에서 부모 요소를 가지고 있고 그것의 자식 요소에 대한 참조를 유지합니다.

An Element has at most one parent Element. An Element’s parent is final and cannot be changed. So you cannot move an Element by changing its parent. Get an Element’s parent with the getter parent. For example, if you have an Element with the name anElement you would refer to its parent element with anElement.parent.

요소는 거의 대부분 하나의 부모 요소를 가집니다. 요소의 부모는 마지막이고 바뀔수 없습니다. 그래서 당신은 부모를 바꾸어서 요소를 이동할 수 없습니다. getter 함수인 parent를 사용해서 해당 요소의 부모를 확인해 보세요. 예를 들면, 당신이 anElement라고 하는 이름의 요소를 가지고 있다면 당신은 anElement.parent를 사용해서 부모 요소를 참조할 수 있습니다.

An Element maintains references to its child elements in a list. List is a class in the dart:core library that implements an indexable collection with a length. A list can be of fixed size or extendable.

요소는 리스트 상에 있는 자식 요소에 대한 참조를 유지합니다. List는 길이를 이용해서 색인할 수 있는(찾아갈 수 있는) 컬렉션을 구현한 dart:core 라이브러리에 있는 클래스입니다. 리스트는 고정 크기일 수도 있고 확장할 수도 있습니다.

List is an example of a generic (or parameterized) type—a type that can declare formal type parameters. This means that a list can be declared to contain only objects of a particular type. For example:

List는 제너릭또는 매개변화?) 타입의 예입니다. 제너릭 타입은 정규타입의 파라미터를 선언할 수 있다는 것을 뜻합니다. 이것은 다시 말해서, List 는 특정 타입의 객체들로만 이루어지게 만들수 있다는 것을 의미 합니다. 아래의 예를 보면 이해가 되실 겁니다.


List declaration

List description

List<String>

list of strings

List<int>

list of integers

List<Element>

list of elements


An Element maintains references to its child element in a List<Element>, which your Dart code can refer to with the getter children. The List class has various methods and operators whereby you can refer to each child Element individually, iterate over the list, and add and remove elements.

Element 클래스는 List<Element>의 자식 요소들에 대한 참조를 유지합니다. 그것은 당신의 Dart 코드에서 getter 함수인 children을 사용해서 참조할 수 있다는 뜻입니다. List 클래스는 각각의 개별적으로 자식 Element에 대해서 참조할 수 있고 List 전체를 반복하고 요소를 추가하거나 삭제할 수 있는 다양한 함수와 연산자를 가지고 있습니다.

You can change the tree structure by adding children to and removing children from an Element’s list of children.

당신은 리스트에서 자식 요소를 추가하고 제거함으로서 트리 구조를 변경할 수 있습니다.

When you change an Element or its child Elements in your Dart program, you change the DOM and therefore the web page. The browser re-renders the page automatically.

당신이 Dart 프로그램에서 자식 요소또는 요소를 변경할때 DOM에서 변경이 일어나고 그래서 웹페이지도 변경이 됩니다. 그리고 브라우저는 자동으로 페이지를 다시 랜더링합니다.

Setting up the page in HTML
HTML에서 페이지 설정하기.

Let’s take a look at the todo app to see how it dynamically adds an element to the DOM and displays a new item in the list of things to do.

DOM에서 어떻게 요소를 동적으로 추가하고 할일 목록에 새로운 아이템이 어떻게 나타나는지 todo 앱을 한 번 봅시다.

The HTML code for the todo app sets up the initial HTML page, and thereby the initial DOM tree. You could get the same results using Dart code, but it’s usually better to define the primary page elements in HTML code (easier to read, quicker to load).

todo 앱의 HTML 코드는 초기에 HTML 페이지를 설정합니다.그렇게 함으로써 초기 DOM 트리구조가 설정이 됩니다. 당신은 Dart 코드를 사용해서 같은 결과를 얻을 수 있지만 일반적으로 HTML 코드를 사용해서 초기 페이지를 정의 하는것이 훨씬 좋습니다. (읽기도 쉽고 로딩하는데도 빠름)

The following diagram shows a partial DOM tree for the todo app.

다음의 그림은 todo 앱에서 부분적인 DOM 구조를 보여줍니다.

Of interest are the two page elements that have IDs: to-do-input and to-do-list. The first identifies the <input> element into which the user types. The second identifies the <ul> (unordered list) element containing the task items. Dart code adds elements to this list whenever the user enters text into the input element.

우리가 관심 가져야 부분은 to-do-input과 to-do-list라는 ID를 가지고 있는 2개의 요소입니다. 첫번째 ID는 사용자 타입의  <input>태그를 식별하는 것입니다. 그리고 두번째 ID는 작업 아이템이 들어갈 자리인 <ul>을 식별하는 것입니다. Dart 코드는 이 리스트에 요소를 추가할 것입니다.사용자가 input 요소에 텍스트를 넣을때 말이죠.


Getting an element from the DOM
Dom에서 요소 가져오기.

The following diagram shows the Dart code for the todo app.

다음 그리음은 todo 앱에서 Dart 코드를 보여줍니다.

The main() function uses dart:html’s top-level querySelector() function to get the interesting elements from the DOM. Because calling querySelector() isn’t free, if a program refers to an element more than once it should stash a reference to the element.

main() 함수는  DOM에서 우리가 관심 있어하는 요소를 가져오기 위해서 dart:html의 top-level 함수인 querySelector() 를 사용합니다. querySelector() 함수는 공짜가 아니기 때문에(함수 호출은 시스템 자원을 소비하기 때문에), 프로그램이 한 번 이상 요소를 참조한다면 그 요소를 변수에 넣어둬야합니다.

This program stashes a reference to the input element in a top-level variable called toDoInput. The unordered list is in the top-level variable toDoList.

이 프로그램은 최상위 변수인 toDoInput에 input 요소의 참조를 넣어둡니다. 정렬하지 않는 리스트(ul 태그를 말함) 최상위 변수인 toDoList 변수에 담아둡니다.

Note the types of these variables: InputElement and UListElement. These are both subclasses of Element. The dart:html library has dozens of Element subclasses, many of which correspond to certain HTML tags. This program uses three:

이 변수의 타입을 알아두세요. InputElement와 UListElement. 이 클래스들은 Element의 하위 클래스 입니다. dart:html 라이브러리에는 HTML 태그와 일지하는 수많은 Element 하위 클래스들이 있습니다. 이번 todo 앱의 아래의 3개를 사용합니다.

HTML tag

Dart class

<input>

InputElement

<ul>

UListElement

<li>

LIElement

Registering an event handler
이벤트 핸들러 등록하기.

When a user enters text into the input field, a change event fires, indicating that the value in the input field has just changed. The todo app defines a function, addToDoItem(), that can handle these change events. The following code connects addToDoItem() to the input field:

사용자가 input 필드에 텍스트를 넣을때, input 필드 안에 있는 값이 변경되었음을 감지하는  이벤트가 발생합니다.

Rather than dissect this busy line of code, think of it as a Dart idiom for adding an event handler to an Element.

이 코드를 해부하는것 보다, Element 객체에 이벤트 핸들러를 추가하는 Dart의 사상(관용구? 작풍?)에 대해 생각해 보세요.

A change event is just one of many different types of events that an input element can generate. For example, you can use click to handle mouse clicks, or keyDown for when the user presses a key on the keyboard.

change 이벤트는 input 요소가 발생시킬수 있는 수 많은 이벤트들 중에 단 하나에 불과합니다. 예를 들어, 당신은 마우스로 클릭을 핸들링 하기 위해서는 click 이벤트를 사용할 수 있고, 또는 키보드로 키를 눌렀을때는 kewyDown 이라는 이벤트를 사용할 수 있습니다.


About EventListener functions
이벤트 리스너 함수에 대해서

The argument passed to the listen() method is a callback function of type EventListener. EventListener is a typedef defined in the dart:html library as follows:

listen() 함수에 전달하는 인자는 EventListener라고 하는 타입의  콜백 함수 입니다. EventListener는 아래에 보는 바와 같이  dart:html 라이브러에 정의되어 있는 타입 입니다.

typedef void EventListener(Event event)

As you can see, an EventListener returns no value (void) and takes an Event object as an argument. Any function with this signature is an EventListener. Based on its signature, the addToDoItem() function is an EventListener.

보는대로, EventListener은 아무것도 리턴하지 않고 인자로서 Event 객체만을 받습니다. 이런 모습을 가지고 있는 함수는 이벤트 리스너 입니다. 이런 모습에 기초해서, addToDoItem() 함수는 이벤트 리스너 입니다.

void addToDoItem(Event e) { ... }

The Event object passed into an EventListener function carries information about the Event that occurred. For example, the Event object knows which Element fired the event, and when. For location-specific events such as mouse clicks, the Event object also knows where the event occurred.

이벤트 리스너 함수에 전달된 이벤트 객체는 발생한 이벤트에 대한 정보를 전달합니다. 예를 들면, 이벤트 객체는 어떤 요소가 언제 이벤트를 발생했는지에 대한 정보를 가지고 있습니다.  마우스 클릭과 같은 특정 위치 이벤트를 발생시키는 이벤트 객체는 어디서 그 이벤트가 발생했는지에 대한 정보도 가지고 있습니다.

The addToDoItem() function ignores the Event object passed to it.

addToDoItem()함수는 전달된 이벤트 객체를 무시합니다.

Adding an element to the DOM tree
DOM 트리에 요소 추가하기.

The change event handler has the following code:

change 이벤트 핸들러는 아래의 코드와 같습니다.

The final line of code is where the DOM gets changed.

코드의 마지막 줄이 DOM의 변화시킵니다.

An Element keeps references to all of its children in a list called children. By adding and removing elements to and from this list, the code changes the DOM. When the DOM changes, the browser re-renders the browser page. The effect, in our todo app, is that a new bullet item appears in the to do list.

요소는 children 이라고 리스트 안에 모든 자식들의 참조값을 가지고 있습니다. 이 리스트에 요소를 추가하고 삭제함으로서 DOM이 변화되고, 그리고 DOM이 변화될때 그 때 브라우저는 웹 페이지를 다시 랜더링 합니다. todo 앱에서 이 효과는 할일 목록에 새로운 bullet 아이템을 추가합니다.


Styling the page elements
페이지 요소에 스타일 입히기.

Let’s take a look at the CSS file for this app.

아래의 CSS 파일을 한 번 보자.

This code uses three different kinds of CSS selectors. The first is an HTML element selector that matches the <body> element and sets some basic style attributes, such as the background color, for the entire page. Next in the file are two ID selectors: #to-do-input controls the appearance of the input field and #to-do-list sets the appearance of the unordered list element in general. The elements in the list are controlled by the final rule, which uses both an ID selector and an HTML selector. This rule matches all <li> elements in the element with the ID to-do-list, thus styling each item in the to do list.

이 코드는 3개의 다른 CSS 셀렉터를 사용합니다. 첫번째 사용 방법은 페이지 전체에 해당하는  <body> 요소와 매칭되는 HTML 요소 셀렉터 입니다. 그리고  <body>에 해당하는  CSS 안에는 background color와 같은 기본적인 스타일 속성만이 설정되어 있습니다.  <body> 바로 다음에 있는 ID 셀렉터를 사용하는 2가지를 봅시다. 먼저 #to-do-input은 input 필드의 모습을 제어하고 #to-do-list는 정렬되지 않는 list 요소(ul 태그)의 모습을 설정합니다. 리스트의 요소(li 태그)들은 마지막 줄에 있는 속성에 의해 제어 됩니다. 마지막 줄은 ID 셀렉터와 HTML 셀렉터 2개 다를 사용합니다. 이 규칙은 ID가 to-do-list인 요소의 모든 <li> 요소와 매칭됩니다.


Moving elements within the DOM tree
DOM 트리에 새로운 요소 옮기기.

Here’s an example that shows how to move an element within the DOM. Try it! Form a word by clicking the letter tiles.
DOM에서 요소를 어떻게 옮기는지 보여주는 예가 입니다. 한 번 해보세요! 문자를 클릭해서 올바른 단어로 완성하세요.

(실행되는 예제는 원본 URL: https://www.dartlang.org/docs/tutorials/add-elements/ 에 있음)

When the program starts, it creates one button element for each of seven randomly selected letters. The program adds each button to a DOM element—a simple <div> element identified by the CSS selector letterpile—with a call to letterpile.children.add().

프로그램이 시작할때, 랜덤으로 7개의 선택된 각각의 버튼 요소를 만듭니다. 프로그램은 ID가 letterpile로 식별할수 있는 간단한 <div> 요소인 DOM 요소에 letterpile.children.add()함수를 호출하여 각각의 버튼을 추가합니다.

Each button element in the letter pile has a mouse click handler called moveLetter(). If the button is in the letterpile, the mouse click handler moves the button to the end of the word. If the button is in the word, the mouse click handler moves the button back to the letter pile.

letter pile(div 태그) 안에 있는 각각의 버튼 요소는 moveLetter() 이라고 하는 마우스 클릭 이벤트 핸들러를 호출합니다.버튼이 letterpile안에 있다면, 마우스가 click 핸들러는 버튼을 단어의 제일 끝으로 옮깁니다. 만약 버튼이 word안에 있다면, 마우스 click 핸들러는 해당 버튼을  letter pile로 다시돌려보냅니다.

To move the button from the letter pile to the word or back, the code simply adds the button to a DOM element that is different from the button’s current parent. Because an element can have only one parent, adding the button to a different parent automatically removes it from its previous parent.

letter pile(글자 무더기)에서 버튼을 word 쪽이나 아니면 다시 letter pile쪽으로 옮기기 위해서 코드는 버튼의 현재 부모 요소에서 다른 DOM 요소에 간단하게 버튼을 추가합니다. 요소는 단 하나의 부모만을 가질수 있기 때문에 이전 부모로 부터는 자동으로 제거가 되고 다른 부모에 붙게 됩니다.


Other resources#

  • You can find more information about the DOM and CSS in Dart: Up and Running, which also provides thorough coverage of the Dart language, libraries, and tools.

What next?

The next tutorial, Remove DOM Elements, describes how to remove elements from the DOM and items off your todo list.

다음 튜토리얼 DOM  요소 제거하기는 할일 목록에서 아이템과 DOM에서 요소를 어떻게 제거하는지 설명할 것 입니다.


300x250

'개발 > dart' 카테고리의 다른 글

6. Defined a Custom Element  (0) 2014.03.02
5. Install Shared Packages  (0) 2014.03.02
4. Remove DOM Elements  (0) 2014.03.02
2. Connect Dart & HTML  (0) 2014.03.02
1. get started  (0) 2014.03.02

댓글