RIOT.JS-Mixin
通过Mixin,我们可以在标签之间共享通用功能。Mixin 可以是函数、类或对象。考虑每个标签都应使用的身份验证服务的情况。
定义 Mixin - 在调用 mount() 之前使用 riot.mixin() 方法定义 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!'
}
}
});
初始化 mixin - 在每个标签中初始化 mixin。
this.mixin('authService')
使用 mixin - 初始化后,mixin 可以在标签内使用。
this.message = this.login("admin","admin");
例子
以下是完整的示例。
自定义8Tag.tag
<custom8Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin","admin")
</script>
</custom8Tag>
自定义9Tag.tag
<custom9Tag>
<h1>{ message }</h1>
<script>
this.mixin('authService')
this.message = this.login("admin1","admin")
</script>
</custom9Tag>
定制8.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>
这将产生以下结果 -