RIOT.JS - 可观察对象



可观察对象机制允许 RIOT 从一个标签向另一个标签发送事件。以下 API 对于理解 RIOT 可观察对象很重要。

  • riot.observable(element) − 向给定的对象元素添加观察者支持,如果参数为空,则创建一个新的可观察对象实例并返回。之后,该对象能够触发事件并监听事件。

var EventBus = function(){
   riot.observable(this);
}
  • element.trigger(events) − 执行监听给定事件的所有回调函数。

sendMessage() {
   riot.eventBus.trigger('message', 'Custom 10 Button Clicked!');    
}
  • element.on(events, callback) − 监听给定事件并在每次触发事件时执行回调。

riot.eventBus.on('message', function(input) {      
   console.log(input);
});

示例

以下是完整示例。

custom10Tag.tag

<custom10Tag>
   <button onclick = {sendMessage}>Custom 10</button>
   <script>
      sendMessage() {
         riot.eventBus.trigger('message', 'Custom 10 Button Clicked!');    
      }
   </script>    
</custom10Tag>

custom11Tag.tag

<custom11Tag>
   <script>
      riot.eventBus.on('message', function(input) {      
         console.log(input);
      });
   </script>    
</custom11Tag>

custom9.htm

<html>
   <head>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script>
   </head>
   <body>
      <custom10Tag></custom10Tag>
      <custom11Tag></custom11Tag>
      <script src = "custom10Tag.tag" type = "riot/tag"></script>
      <script src = "custom11Tag.tag" type = "riot/tag"></script>
      <script>
         var EventBus = function(){
            riot.observable(this);
         }
         riot.eventBus = new EventBus();
         riot.mount("*");
      </script>
   </body>
</html>

将产生以下结果 −

广告
© . All rights reserved.