RIOT.JS教程:Observables机制

Observables机制允许RIOT将事件从一个标签发送到另一个标签。遵循以下API对于了解RIOT可观察性很重要。

  • riot.observable(element) -添加对给定对象元素的Observer支持,或者如果参数为空,则创建并返回一个新的observable实例。此后,该对象便能够触发并监听事件。
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>

预览效果:

RIOT.JS教程:Observables机制

作者:terry,如若转载,请注明出处:https://www.web176.com/riotjs/2179.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年3月30日 下午4:51
下一篇 2021年3月31日 下午3:39

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注