
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");
示例
以下是完整示例。
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>
這將產生以下結果 −
廣告