RIOT.JS-ミックスイン
Mixinを通じて、タグ間で共通の機能を共有できます。Mixinは、関数、クラス、またはオブジェクトにすることができます。各タグが使用する必要がある認証サービスのケースを考えてみましょう。
Define Mixin − mount()を呼び出す前に、riot.mixin()メソッドを使用してミックスインを定義します。
riot.mixin('authService', {
init: function() {
console.log('AuthService Created!')
},
login: function(user, password) {
if(user == "admin" && password == "admin"){
return 'User is authentic!'
}else{
return 'Authentication failed!'
}
}
});
Initialize mixin −各タグでミックスインを初期化します。
this.mixin('authService')
Use mixin −初期化後、ミックスインをタグ内で使用できます。
this.message = this.login("admin","admin");
例
以下は完全な例です。
custom8Tag.tag
<custom8Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin","admin")
</script>
</custom8Tag>
custom9Tag.tag
<custom9Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin1","admin")
</script>
</custom9Tag>
custom8.htm
<html>
<head>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script>
</head>
<body>
<custom8Tag></custom8Tag>
<custom9Tag></custom9Tag>
<script src = "custom8Tag.tag" type = "riot/tag"></script>
<script src = "custom9Tag.tag" type = "riot/tag"></script>
<script>
riot.mixin('authService', {
init: function() {
console.log('AuthService Created!')
},
login: function(user, password) {
if(user == "admin" && password == "admin"){
return 'User is authentic!'
}else{
return 'Authentication failed!'
}
}
});
riot.mount("*");
</script>
</body>
</html>
これにより、次の結果が生成されます-