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>

这将产生以下结果 −

广告