
Observables mechanism allows RIOT to send events from one tag to another. Following APIs are important to understand RIOT observables.
riot.observable(element) − Adds Observer support for the given object element or if the argument is empty a new observable instance is created and returned. After this the object is able to trigger and listen to events.
var EventBus = function(){
riot.observable(this);
}
element.trigger(events) − Execute all callback functions that listen to the given event.
sendMessage() {
riot.eventBus.trigger('message', 'Custom 10 Button Clicked!');
}
element.on(events, callback) − Listen to the given event and execute the callback each time an event is triggered.
riot.eventBus.on('message', function(input) {
console.log(input);
});
Following is the complete example.
<custom10Tag>
<button onclick = {sendMessage}>Custom 10</button>
<script>
sendMessage() {
riot.eventBus.trigger('message', 'Custom 10 Button Clicked!');
}
</script>
</custom10Tag>
<custom11Tag>
<script>
riot.eventBus.on('message', function(input) {
console.log(input);
});
</script>
</custom11Tag>
<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>
This will produce following result −