Riot 프레임워크 알아보기. (2/6) Tag

tag

태그

Riot의 Tag는 UI를 만드는 기본 요소이다. 좀 더 확장된 Todo태그를 보자.

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
32
33
34
35
36
37
38
39
<todo>
<h3>{ opts.title }</h3>
<ul>
<li each={ items }>
<label class={ completed: done }>
<input type="checkbox" checked={ done } onclick={ parent.toggle }> { title }
</label>
</li>
</ul>
<form onsubmit={ add }>
<input name="input" onkeyup={ edit }>
<button disabled={ !text }>Add #{ items.length + 1 }</button>
</form>
<script>
this.items = opts.items
edit(e) {
this.text = e.target.value
}
add(e) {
if (this.text) {
this.items.push({ title: this.text })
this.text = this.input.value = ''
}
}
toggle(e) {
var item = e.item
item.done = !item.done
return true
}
</script>
</todo>

이 예제는 이곳에서 실행결과를 확인해 볼 수 있다. Riot태그 컴포넌트는 마크업과 자바스크립트 로직의 조합이다. 심지어, <script>태그를 생략할 수도 있다. Expression내에 따옴표도 생략가능 하다. <foo bar={ baz }>는 <foo bar=”{ baz }”>과 같다.
ES6 화살표 함수처럼 methodName() { } 는 this.methidName = function() {}.bind(this) 와 같이 실행시에 변환되어 해석된다. 그러므로, this는 항상 현재 태그의 인스턴스를 가리킨다.

마운트

태그가 생성되면 페이지에서 다음과 같이 마운트를 할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<body>
<!-- place the custom tag anywhere inside the body -->
<todo></todo>
<!-- include riot.js -->
<script src="riot.min.js"></script>
<!-- include the tag -->
<script src="todo.js" type="riot/tag"></script>
<!-- mount the tag -->
<script>riot.mount('todo')</script>
</body>

이때, <todo/>와 같이 self-closing태그는 지원되지 않는다.

Riot에서 DOM에 접근하려면 Riot Tag의 Life Cycle에 대해 약간 알아 둘 필요가 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<example-tag>
<p id="findMe">Do I even Exist?</p>
<script>
var test1 = document.getElementById('findMe') // (1)
console.log('test1', test1) // Fails
this.on('update', function(){
var test2 = document.getElementById('findMe') (2)
console.log('test2', test2) // Succeeds, fires on every update
})
this.on('mount', function(){
var test3 = document.getElementById('findMe') (3)
console.log('test3', test3) // Succeeds, fires once (per mount)
})
</script>
</example-tag>

첫번째는 실패이고, 나머지는 성공이다. 2번과 3번의 차이는 태그가 업데이트될때마다 실행되느냐 최초 마운트시에 한번만 실행되느냐의 차이이다. 이 외에도, 몇가지 이벤트들이 더 존재한다.

  • before-mound: 마운트 되기전 한번
  • mount: 마운트 된후 한번
  • update: 업데이트 되기전 매번
  • updated: 업데이트 된후 매번
  • before-unmount: 삭제되기전 한번
  • unmount : 삭제 된후 한번
  • * : 모든 이벤트

마운트할때 두번째 인자에 데이터를 넘겨줄 수 있다.

1
2
3
<script>
riot.mount('todo', { title: 'My TODO app', items: [ ... ] })
</script>

간단한 자바스크립트 객체에서 Flux Store까지 무엇이든 넘겨줄 수 있다.

1
2
3
4
5
6
7
8
9
<my-tag>
<!-- Options in HTML -->
<h3>{ opts.title }</h3>
// Options in JavaScript
var title = opts.title
</my-tag>

이렇게 넘겨받은 데이터는 스크립트내부에서나 HTML에서 opts객체로 사용할 수 있다. <script>…</script> 태그는 생략해도 된다.