Riot 프레임워크 알아보기. (3/6) Mixin과 yield

mixin

믹스인

믹스인은 태그들간의 기능을 공유하기 쉽도록 해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var OptsMixin = {
init: function() {
this.on('updated', function() { console.log('Updated!') })
},
getOpts: function() {
return this.opts
},
setOpts: function(opts, update) {
this.opts = opts
if (!update) this.update()
return this
}
}
<my-tag>
<h1>{ opts.title }</h1>
this.mixin(OptsMixin)
</my-tag>

이 믹스인은 my-tag 태그 인스턴스의 opts객체에 접근할 수 있게 해준다. 단, init 함수는 외부에서 접근할 수 없다. 이 함수는 태그에 믹스인이 로딩되기전에 초기화를 하는 함수이다. 이렇게, 믹스인은 태그를 확장하기도 하고, 반복되는 작업을 위해 믹스인을 공유할수도 해준다.

공유 믹스인 (Shared Mixin)

믹스인을 공유하기 위해, riot.mixin API를 제공한다. 공유할 믹스인을 다음과 같이 등록할 수 있다.

1
riot.mixin('mixinName', mixinObject)

이 믹스인을 태그에서 사용하려면 공유한 키와 mixin()메소드를 사용하면 된다.

1
2
3
4
5
<my-tag>
<h1>{ opts.title }</h1>
this.mixin('mixinName')
</my-tag>

전역 믹스인 (Global Mixin)

말그대로 모든 태그에서 사용할 수 있다.

1
riot.mixin(mixinObject)

공유 믹스인과 달리, 전역의 경우 모든 마운트된 태그에 자동으로 로딩된다. 만일, 전역 믹스인에 키를 부여하고 싶다면 세번째 파라미터를 ‘true’로 주면 된다.

1
riot.mixin('mixinName', mixinObject, true)

전역은 가끔 네임스페이스를 오염시킬 수 있어 좋은 방법이 아니다. 가급적 공유 믹스인을 사용하는 방식으로 구성하는 것이 좋다.

yield

Riot은 <yield>라는 태그를 내장하고 있다. 이 특별한 태그는 어떤 태그 컴포넌트에든 HTML컨텐츠를 동적으로 적용하고 런타임시에 컴파일된다.

1
2
3
4
5
<alert>
<div class={alert:true, 'alert-warning': opts.warning , 'alert-danger': opts.danger}>
<yield />
</div>
</alert>

이런 오류 메시지 처리시에도 사용될 수 있다.

1
2
3
4
5
<alert warning="true">
<p>
<strong>Name is required field</strong>
</p>
</alert>

결과는 아래와 같다.

1
2
3
4
5
6
7
<alert>
<div class='alert-warning'>
<p>
<strong>Name is required field</strong>
</p>
</div>
</alert>

이런 Form Validation외에도 yield태그는 다양한 용도로 사용될 수 있다.

1
2
3
4
5
<my-post>
<h1>{ opts.title }</h1>
<yield/>
this.id = 666
</my-post>

이렇게 my-post 태그를 생성하고 아래와 같이 호출하면

1
2
3
<my-post title="What a great title">
<p id="my-content-{ id }">My beautiful post is just awesome</p>
</my-post>

결과는 아래와 같다.

1
2
3
4
<my-post>
<h1>What a great title</h1>
<p id="my-content-666">My beautiful post is just awesome</p>
</my-post>