RIOT.JS - 可观察的
Observables 机制允许 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);
});
例子
以下是完整的示例。
自定义10Tag.tag
<custom10Tag>
<button onclick = {sendMessage}>Custom 10</button>
<script>
sendMessage() {
riot.eventBus.trigger('message', 'Custom 10 Button Clicked!');
}
</script>
</custom10Tag>
自定义11Tag.tag
<custom11Tag>
<script>
riot.eventBus.on('message', function(input) {
console.log(input);
});
</script>
</custom11Tag>
定制9.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>
这将产生以下结果 -