RIOT.JS - Mixin

Grâce à Mixin, nous pouvons partager des fonctionnalités communes entre les balises. Mixin peut être une fonction, une classe ou un objet. Prenons un cas de service d'authentification que chaque balise devrait utiliser.

  • Define Mixin - Définissez mixin en utilisant la méthode riot.mixin () avant d'appeler mount ().

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 - Initialisez mixin dans chaque tag.

this.mixin('authService')
  • Use mixin - Après l'initialisation, mixin peut être utilisé dans le tag.

this.message = this.login("admin","admin");

Exemple

Voici l'exemple complet.

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>

Cela produira le résultat suivant -